13

给定以下代码设置:

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

List<Foo> foos = GetListOfFoosFromSomewhere();

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

string[] distinctMyStrings = ?
4

1 回答 1

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.

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

于 2009-10-14T20:04:29.143 回答