给出以下代码设置:
public class Foo {
List<string> MyStrings { get; set; }
}
List<Foo> foos = GetListOfFoosFromSomewhere();
如何使用LINQ获取所有Foo实例中MyStrings中所有不同字符串的列表?我觉得这应该很容易,但不能完全理解。
string[] distinctMyStrings = ?
答案 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。这是非常有用的,有很好的例子!