没有使用foreach循环就可以针对以下问题定义LINQ语句吗?
public class GroupObject { public String name; public List<String> letters; public void test() { List<GroupObject> myGroups = new List<GroupObject> { new GroupObject { name="test1", letters=new List<String>{"x","y","z"} }, new GroupObject { name="test2", letters=new List<String>{"l","m","n"} }, new GroupObject { name="test3", letters=new List<String>{"m","x","z"} } }; // LINQ problem 1: how to get a list of all 9 letters // List<string> allLetters = (from ...).ToList(); // LINQ problem 2: how to get a list of all 6 DISTINCT letters // List<string> allDistictLetters = (from ...).ToList(); } }
在写这个问题时,我找到了解决问题的办法。我仍然会发布(并回答)这个问题,因为这个问题对我来说真是个麻烦。而且我在这里没有找到合适的现有问题。
乔,尤文
相信SelectManyand可以解决这个问题Distinct!
SelectMany
Distinct
var allLetters = myGroups.SelectMany(go => go.letters); var allUniqueLetters = allLetters.Distinct();
第二个变量名称具有误导作用。除其他字母外,它还会返回的一个实例"m",该实例在原始集合中 不是 唯一的;)
"m"