代码之家  ›  专栏  ›  技术社区  ›  Brian Vallelunga Linda Lawton - DaImTo

使用LINQ to对象在所有嵌套集合中选择不同的值?

  •  11
  • Brian Vallelunga Linda Lawton - DaImTo  · 技术社区  · 15 年前

    给定以下代码设置:

    public class Foo {
     List<string> MyStrings { get; set; }
    }
    
    List<Foo> foos = GetListOfFoosFromSomewhere();
    

    如何使用LINQ在所有Foo实例中获得MyString中所有不同字符串的列表?我觉得这应该很容易,但我不太明白。

    string[] distinctMyStrings = ?
    
    1 回复  |  直到 15 年前
        1
  •  15
  •   Vitaliy    15 年前
     // 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.
    

    我还强烈建议阅读关于可枚举扩展方法的MSDN。这是非常翔实的,并有伟大的例子!