Reputation: 199
I have a file that contains information parsed from an Excel Sheet:
class ProfileRecord
{
public string ProfileCode { get; set; }
public string DID { get; set; }
public string AppName { get; set; }
public string lvl1 { get; set; }
public string lvl2 { get; set; }
public string lvl3 { get; set; }
public string lvl4 { get; set; }
}
In another Class, I send a list of these records for analysis. One thing I want to do is make a var that finds all of the matching ProfileCodes. So, say part of the excel sheet is :
Name Profile Code
Billy 134
Sally 156
Mary 134
Jimmy 134
Tom 189
Then i would have something (I really dont know):
var sameProfile = from a in profileList
where ( //some code to group all similar profile codes)
select new
{
name = a.Name
};
If i were to print:
foreach(var p in sameProfile)
{
Console.WriteLine(p.name);
Console.WriteLine("\n");
}
I want to have:
Billy
Mary
Jimmy
Sally
Tom
Printed. I am unsure of how to find all simialr elements and group them using LINQ. Suggestions? Thanks.
Upvotes: 3
Views: 120
Reputation: 149000
You want to use the GroupBy
method:
var results = profileList.GroupBy(a => a.ProfileCode)
.Select(g => g.Select(a => a.Name));
Or in query syntax:
var results =
from a in profileList
group a by a.ProfileCode into g
select g.Select(a => a.Name);
Upvotes: 2
Reputation: 460058
Use Enumerable.GroupBy
:
var profileCodeGroups = profileList
.GroupBy(pr => pr.ProfileCode)
.OrderBy(g => g.Key);
foreach(var grp in profileCodeGroups)
{
foreach(var pr in grp)
Console.WriteLine(pr.Name);
Console.WriteLine("");
}
Upvotes: 5