public class ConsolidatedChild { public string School { get; set; } public string Friend { get; set; } public string FavoriteColor { get; set; } public List 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从列表创建一个列表,该列表按School,Friend和FavoriteColor属性分组。LINQ有可能吗?
请忽略属性,编写代码只是为了帮助解决该问题。
简单:
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(), };
var consolidatedChildren = children .GroupBy(c => new { c.School, c.Friend, c.FavoriteColor, }) .Select(gcs => new ConsolidatedChild() { School = gcs.Key.School, Friend = gcs.Key.Friend, FavoriteColor = gcs.Key.FavoriteColor, Children = gcs.ToList(), });