首页 文章

C#Linq Group By多列[重复]

提问于
浏览
228

这个问题在这里已有答案:

public class ConsolidatedChild
{
    public string School { get; set; }
    public string Friend { get; set; }
    public string FavoriteColor { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public string School { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Friend { get; set; }
    public string Mother { get; set; }
    public string FavoriteColor { get; set; }
}

鉴于上面的两个类,我想使用LINQ从List创建一个List,按School,Friend和FavoriteColor属性分组 . LINQ可以实现吗?

请忽略属性,代码编写只是为了帮助解决问题 .

2 回答

  • 182

    简单:

    var consolidatedChildren =
        from c in children
        group c by new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        } into gcs
        select new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        };
    
  • 357

    给出一个清单:

    var list = new List<Child>()
                    {
                        new Child()
                            {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
                        new Child()
                            {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
                        new Child()
                            {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
                        new Child()
                            {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
                    };
    

    查询看起来像:

    var newList = list.GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
                        .Select(y => new ConsolidatedChild()
                                            {
                                                FavoriteColor = y.Key.FavoriteColor,
                                                Friend = y.Key.Friend,
                                                School = y.Key.School,
                                                Children = y.ToList()
                                            }
                        );
    

    测试代码:

    foreach(var item in newList)
    {
        Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
        foreach(var child in item.Children)
        {
            Console.WriteLine("\t Name: {0}", child.Name);
        }
    }
    

    结果:

    School: School1 FavouriteColor: blue Friend: Bob
             Name: John
             Name: Fred
    School: School2 FavouriteColor: blue Friend: Bob
             Name: Pete
    School: School2 FavouriteColor: blue Friend: Fred
             Name: Bob
    

相关问题