Search code examples
c#linq

Multi nested FirstOrDefault


I have the following model:

public class Stredisko
{
    public string Name { get; set; }
    public ObservableCollection<SubStredisko> Pracoviska { get; set; }
    public ObservableCollection<SubStredisko> Dohodari { get; set; }
}
public class SubStredisko
{
    public string Name { get; set; }
    public string Code { get; set; }

    public VyplatnePasky VyplatnaPaska { get; set; }
    public MzdoveNaklady MzdoveNaklady { get; set; }
    public Poistne Poistne { get; set; }
}

I am now trying to run a super simple LINQ query which should return first element which matches the following condition:

var sStredisko = Strediska.FirstOrDefault(
                    n => n.Pracoviska.FirstOrDefault(x=>x.Name == "somename"));

I Run this condition against: ObservableCollection<Stredisko> Strediska

However for unknown reason (to me) it gives me the following error: Cannot implicitly convert type 'SubStredisko' to 'bool'.

What am I doing wrong?


Solution

  • You're looking for Enumerable.Any:

    var sStredisko = Strediska.FirstOrDefault(
                                  n => n.Pracoviska.Any(x => x.Name == "somename"));
    

    FirstOrDefault will yield the first element that matches the predicate. You want to match against the first element and yield a bool indicating the match has been found, which is what Any does.