LINQ on complex nested observable collection
I have a nested ObservableCollection<Student>
, from which how can I get a particular student based on Id value using LINQ or Lambda ? Here is my Student class:
public class Student
{
public Student()
{
}
public string Name;
public int ID;
public ObservableCollection<Student> StudLists;
}
So each student object can have again student collections and it can go like any number of nested levels. how we can do it LINQ or using Lambda ? I have tried with
var studs = StudCollections.Where(c => c.StudLists.Any(m => m.ID == 122));
But this is not giving exact Student item ? Any idea 开发者_Python百科?
If you mean you want to search all descendants of StudCollections, then you could write an extension method like so:
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;
}
}
}
}
and use it like so:
var students = StudCollections.Descendants(s => s.StudLists).Where(s => s.ID == 122);
If you want one student with a matching id, use:
var student = StudCollections.Descendants(s => s.StudLists).FirstOrDefault(s => s.ID == 122);
if (student != null)
{
// access student info here
}
精彩评论