Linq合并列表 [英] Linq Merge lists

查看:100
本文介绍了Linq合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课:

    public class Foo
    {
        public int A { get; set; }
        public List<Bar> Bars { get; set; }
    }

我有IEnumerable<Foo>.我想按A进行List<Foo>分组,并获得Bars列表,该列表包含Bars中所有要分组的元素.

I've got IEnumerable<Foo>. I would like get List<Foo> grouping by A, and get Bars list, which contais all elements at Bars for group.

所以最终的Foo.Bars应该包含Bar在组中的所有元素

So final Foo.Bars should contains all elements of Bar at group

linq可以吗?

推荐答案

var result = foos.GroupBy(f => f.A)
                 .SelectMany(grp => grp.Select(f => f.Bars));

如Rawling所述,它不会返回IEnumerable<Foo>,因此请尝试以下操作:

As Rawling has mentioned, this returns not an IEnumerable<Foo>, so try this:

IEnumerable<Foo> result = 
            foos.GroupBy(f => f.A)
            .Select(grp => new Foo() { 
                A = grp.Key,
                Bars = grp.SelectMany(ff => ff.Bars).Distinct().ToList()
            });

我不确定您是否想要Bars的独特列表.请注意,您可能需要覆盖类Bar中的EqualsGetHashCode.

I'm not sure whether you want a distinct list of Bars or not. Note that you may need to override Equals and GetHashCode in class Bar.

这篇关于Linq合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆