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

时间:2009-10-14 19:14:24

标签: linq-to-objects collections distinct

给出以下代码设置:

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

List<Foo> foos = GetListOfFoosFromSomewhere();

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

string[] distinctMyStrings = ?

1 个答案:

答案 0 :(得分: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。这是非常有用的,有很好的例子!