Home > Back-end >  Select specific value in multiple dimensions via linq expression in C#
Select specific value in multiple dimensions via linq expression in C#

Time:09-29

I have a problem with a linq expression in C#.

I have an info class which contains an array

public fruits[] fruits { get; set; }

This fruits class contains another set of data:

public anotherSet[] anotherSet { get; set; }

And this class in turn has an id.

public string id { get; set; }

Now I want to perform a match of my variable with the id via a linq expression. Note, of course, that this involves multiple dimensions.
There can be multiple fruits and multiple anotherSet.

I want and alignment like the following:

fruits.anotherset.id == myVariable

the fruit basket is a KeyValuePair with <key, info>
This info object then contains the fruits[].

But something like this doesn't work:

var filteredId = myFruitsBasket.Where(x => x.Value.fruits.Where(x => x.anotherSet.Where(x => x.id == myFruitsId)));

I don't want to filter by the myFruitBasket, but need the array of fruits[].

CodePudding user response:

The result of a lambda expression passed into linq where should be a boolean. consider switching to Any inside your where expression.

myFruitsBasket.Where(x => x.Value.fruits.Any(x => x.anotherSet.Any(x => x.id == myFruitsId))).SelectMany(x => x.Value.fruits) should fix the errors you are getting right now, not sure it will yield the correct results though :)

  • Related