【问题标题】:Select distinct values in all nested collections using LINQ to objects?使用 LINQ to 对象在所有嵌套集合中选择不同的值?
【发布时间】:2009-10-14 19:14:24
【问题描述】:

鉴于以下代码设置:

public class Foo {
 List<string> MyStrings { get; set; }
}

List<Foo> foos = GetListOfFoosFromSomewhere();

如何使用 LINQ 在所有 Foo 实例中获取 MyStrings 中所有不同字符串的列表?我觉得这应该很容易,但不能完全弄清楚。

string[] distinctMyStrings = ?

【问题讨论】:

    标签: linq-to-objects collections distinct


    【解决方案1】:
     // If you dont want to use a sub query, I would suggest:
    
            var result = (
                from f in foos
                from s in f.MyStrings
                select s).Distinct();
    
            // Which is absoulutely equivalent to:
    
            var theSameThing = foos.SelectMany(i => i.MyStrings).Distinct();
    
            // pick the one you think is more readable.
    

    我还强烈建议阅读有关 Enumerable 扩展方法的 MSDN。它信息量很大,并且有很好的例子!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2022-01-14
      相关资源
      最近更新 更多