假设 public class MyClass{ public int ID {get; set; } public string Name {get; set; }} 和 ListMyClass classList = //populate with MyClass instances of various IDs 我可以 ListMyClass result = classList.FindAll(class = class.ID == 123);
public class MyClass { public int ID {get; set; } public string Name {get; set; } }
和
List<MyClass> classList = //populate with MyClass instances of various IDs
我可以
List<MyClass> result = classList.FindAll(class => class.ID == 123);
这将给我一个ID = 123的类的列表.效果很好,看起来很优雅.
现在,如果我有
List<List<MyClass>> listOfClassLists = //populate with Lists of MyClass instances
如何获得筛选列表本身被过滤的筛选列表.我试过了
List<List<MyClass>> result = listOfClassLists.FindAll (list => list.FindAll(class => class.ID == 123).Count > 0);
它看起来很优雅,但不起作用.它只包括类的列表,其中至少有一个类的ID为123,但它包含该列表中的所有MyClass实例,而不仅仅是匹配的实例.
我最终不得不这样做
List<List<MyClass>> result = Results(listOfClassLists, 123); private List<List<MyClass>> Results(List<List<MyClass>> myListOfLists, int id) { List<List<MyClass>> results = new List<List<MyClass>>(); foreach (List<MyClass> myClassList in myListOfLists) { List<MyClass> subList = myClassList.FindAll(myClass => myClass.ID == id); if (subList.Count > 0) results.Add(subList); } return results; }
完成工作,但不是那么优雅.只是寻找更好的方法在列表列表上进行FindAll.
肯
MyClass a = new MyClass() { ID = 123, Name = "Apple" }; MyClass b = new MyClass() { ID = 456, Name = "Banana" }; MyClass c = new MyClass() { ID = 789, Name = "Cherry" }; MyClass d = new MyClass() { ID = 123, Name = "Alpha" }; MyClass e = new MyClass() { ID = 456, Name = "Bravo" }; List<List<MyClass>> lists = new List<List<MyClass>>() { new List<MyClass>() { a, b, c }, new List<MyClass>() { d, e }, new List<MyClass>() { b, c, e} }; var query = lists .Select(list => list.Where(item => item.ID == 123).ToList()) .Where(list => list.Count > 0).ToList();
查询将是List< List< MyClass>>保存通过测试的MyClass对象列表.乍一看,它看起来乱序,其中Where扩展位于Select之后,但内部列表的转换需要先发生,这就是Select扩展中发生的情况.然后由Where过滤.