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


鉴于以下代码设置:

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

List<Foo> foos = GetListOfFoosFromSomewhere();

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

string[] distinctMyStrings = ?

3717
2017-10-14 19:14


起源



答案:


 // 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。这是非常翔实的,有很好的例子!


14
2017-10-14 20:04