【LINQ】Select与SelectMany的区别

Select() 和 SelectMany() 的工作都是依据源值生成一个或多个结果值。
Select() 为每个源值生成一个结果值。因此,总体结果是一个与源集合具有相同元素数目的集合。与之相反,SelectMany() 将生成单一总体结果,其中包含来自每个源值的串联子集合。作为参数传递到 SelectMany() 的转换函数必须为每个源值返回一个可枚举值序列。然后,SelectMany() 将串联这些可枚举序列以创建一个大的序列。

private class NamedEntity
{
    public NamedEntity(int id, string name) { this.ID = id; this.Name = name; }
    public int ID { get; set; }
    public string Name { get; set; }
}

public Window()
{
    InitializeComponent();

    NamedEntity[] list1 = { new NamedEntity(1, "Albert"), new NamedEntity(2, "Burke"), new NamedEntity(3, "Connor") };
    NamedEntity[] list2 = { new NamedEntity(2, "Albert was here"), new NamedEntity(3, "Burke slept late"), new NamedEntity(4, "Happy") };
    IList<NamedEntity[]> l = new List<NamedEntity[]>() { list1, list2 };
    IList<NamedEntity> tokens = l.SelectMany(a => a).ToList();
    var grp = tokens.GroupBy(a => a.ID);
    IList<NamedEntity> result = grp.SelectMany(a => a.Take(1)).ToList();
}

 

posted @ 2019-09-29 19:08  Chr☆s  阅读(2330)  评论(0编辑  收藏  举报