Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi nested FirstOrDefault

Tags:

c#

linq

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?

like image 847
Robert J. Avatar asked Feb 18 '26 17:02

Robert J.


1 Answers

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.

like image 99
Yuval Itzchakov Avatar answered Feb 21 '26 09:02

Yuval Itzchakov