Using List <Person> Distinct () to return 2 values
I have a class Person
with properties Name
and AreaID
.
public class Person
{
public string Name;
public int AreaID;
// snip
}
I have List<Person>
with potential for hundreds of Person objects in a list. e.g. 100 people with AreaID = 1 and 100 people with AreaID = 2
I want to return a separate list of AreaIDs and how many people have that AreaID.
For example, AreaID = 1 person. = 100 AreaID = 2 people = 100
source to share
It sounds like you want to group by area ID:
var groups = from person in persons
group 1 by person.AreaID into area
select new { AreaID = area.Key, Persons = area.Count() };
I use "group 1" to indicate that I don't really care about the data in each group - just the account and key.
It's inefficient in that it has to buffer all the results for grouping - you should be fine with using Reactive LINQ in .NET 4.0 to do this more efficiently, or you can certainly use push LINQ if you like. Again, for relatively small datasets this probably doesn't matter :)
source to share
Unexpectedly, no one recommended canceling Equals
and GetHashCode
. If you do, you can do the following:
List<Person> unique = personList.Distinct();
Or even
List<Person> areaGroup = personList.GroupBy(p => p.AreaID);
List<Person> area1Count = personList.Where(p => p.AreaID == 1).Count();
This gives you more flexibility - no need for a useless anonymous class.
source to share
Instead of using it alone, use GroupBy or the more succinct LINQ operator:
var results = from p in PersonList
group p by p.AreaID into g
select new { AreaID=g.Key, Count=g.Count() };
foreach(var item in results)
Console.WriteLine("There were {0} items in Area {1}", item.Count, item.AreaID);
source to share
var people = new List<Person>();
var q = from p in people
group p by p.AreaId into g
select new { Id = g.Key, Total = g.Count() };
people.Add(new Person { AreaId = 1, Name = "Alex" });
people.Add(new Person { AreaId = 1, Name = "Alex" });
people.Add(new Person { AreaId = 2, Name = "Alex" });
people.Add(new Person { AreaId = 3, Name = "Alex" });
people.Add(new Person { AreaId = 3, Name = "Alex" });
people.Add(new Person { AreaId = 4, Name = "Alex" });
people.Add(new Person { AreaId = 2, Name = "Alex" });
people.Add(new Person { AreaId = 4, Name = "Alex" });
people.Add(new Person { AreaId = 1, Name = "Alex" });
foreach (var item in q)
{
Console.WriteLine("AreaId: {0}, Total: {1}",item.Id,item.Total);
}
source to share
Something like this, perhaps?
List<Person> persons = new List<Person> ();
persons.Add (new Person (1, "test1"));
persons.Add (new Person (1, "test2"));
persons.Add (new Person (2, "test3"));
var results =
persons.GroupBy (p => p.AreaId);
foreach( var r in results )
{
Console.WriteLine (String.Format ("Area Id: {0} - Number of members: {1}", r.Key, r.Count ()));
}
Console.ReadLine ();
source to share