【问题标题】:LINQ on complex nested observable collection复杂嵌套可观察集合上的 LINQ
【发布时间】:2011-06-28 21:22:03
【问题描述】:

我有一个嵌套的ObservableCollection<Student>,我如何使用 LINQ 或 Lambda 根据 Id 值从中获取特定学生?这是我的学生课:

public class Student
    {

        public Student()
        {

        }

        public string Name;
        public int ID;
        public ObservableCollection<Student> StudLists;
    }

因此,每个学生对象都可以再次拥有学生集合,并且可以像任意数量的嵌套级别一样。我们如何做到 LINQ 或使用 Lambda ?我试过了

var studs = StudCollections.Where(c => c.StudLists.Any(m => m.ID == 122));

但这不是给出确切的学生项目吗?有什么想法吗?

【问题讨论】:

    标签: linq nested observablecollection


    【解决方案1】:

    如果您的意思是要搜索 StudCollections 的所有后代,那么您可以编写如下扩展方法:

    static public class LinqExtensions
    {
      static public IEnumerable<T> Descendants<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> DescendBy)
      {
        foreach (T value in source)
        {
            yield return value;
    
            foreach (T child in DescendBy(value).Descendants<T>(DescendBy))
            {
                yield return child;
            }
        }
      }
    }
    

    并像这样使用它:

    var students = StudCollections.Descendants(s => s.StudLists).Where(s => s.ID == 122);
    

    如果您想要一个具有匹配 id 的学生,请使用:

    var student = StudCollections.Descendants(s => s.StudLists).FirstOrDefault(s => s.ID == 122);
    
    if (student != null)
    {
      // access student info here
    }
    

    【讨论】:

    • 不仅打败了我,而且有更好的答案。我喜欢这个。此外,对于 OP 的最后一句话,我认为他真正想要的是 FirstSingle(或 OrDefault 变体)
    • foreach (Student ss in students) { } // 当我遍历学生时,它在扩展类的方法 Descendants 中抛出错误。该方法的参数Source为null。
    • @coldwin 然后 StudList 在其中一名学生上为空。除非有特定原因使其为空,否则应将其分配给构造函数中的空列表。
    • 或者,您可以将foreach 循环包装在if (DescendBy(value) != null)
    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    相关资源
    最近更新 更多