从同一列表中选择相似的元素

时间:2013-07-28 22:43:14

标签: c# linq list

我有一个文件,其中包含从Excel工作表中解析的信息:

 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; }
}

在另一个班级中,我发送这些记录的列表进行分析。我想做的一件事是创建一个var,找到所有匹配的ProfileCodes。所以,excel表的一部分是:

Name     Profile Code
Billy    134
Sally    156
Mary     134
Jimmy    134
Tom      189

然后我会有一些东西(我真的不知道):

var sameProfile = from a in profileList
                  where ( //some code to group all similar profile codes)
                  select new
                  {
                    name = a.Name
                  };

如果我要打印:

foreach(var p in sameProfile)
 {
    Console.WriteLine(p.name);
    Console.WriteLine("\n");
  }

我希望:

Billy
Mary
Jimmy

Sally

Tom

印刷。我不确定如何找到所有simialr元素并使用LINQ对它们进行分组。建议? 感谢。

2 个答案:

答案 0 :(得分:5)

使用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("");
}

答案 1 :(得分:2)

您想使用GroupBy方法:

var results = profileList.GroupBy(a => a.ProfileCode)
                         .Select(g => g.Select(a => a.Name));

或者在查询语法中:

var results = 
    from a in profileList
    group a by a.ProfileCode into g
    select g.Select(a => a.Name);
相关问题