Mithun Mithun - 2 months ago 5
C# Question

Using Linq select an item outside an List

I have a list like

{
"Nutrients": [{
"vitamin": "vitamin C",
"potassium": "195mg",
"sodium": "2mg",
"cholesterol": "",
"display_name": "Apple"
}, {
"vitamin": "vitamin B",
"potassium": "176mg",
"sodium": "2mg",
"cholesterol": "",
"display_name": "Grape"
}],
"General_name": "Fruits",
"country_of_origin": "France"


}


{
"Nutrients": [{
"vitamin": "vitamin B",
"potassium": "196mg",
"sodium": "115mg",
"cholesterol": "123mg",
"display_name": "Chicken"

}, {
"vitamin": "vitamin B",
"potassium": "360mg",
"sodium": "53mg",
"cholesterol": "68mg",
"display_name": "Chicken"
}],
"General_name": "Meat",
"country_of_origin": "Denmark"

}


And I need to find the General_name of items which have empty string value for cholesterol.

I tried it using linq lambda expression as

var elements=items.SelectMany(c =>c.Nutrients)
.Where(a => !string.IsNullOrEmpty(a.cholesterol))
.ToList();


My question is how to get the general name from this condition

Answer
var elements = items.Where(x => x.Nutrients.Any(a => !string.IsNullOrEmpty(a.cholesterol)))
   .Select(x => x.GeneralName)
   .ToList();

This will get you a list of all the GeneralName values where the containing Nutrients collection contains a non empty value for cholesterol. Is that what you are looking for?


Edit:

Is there a way I can get the display_name of those items as well?

var elements = items.Where(x => x.Nutrients.Any(a => !string.IsNullOrEmpty(a.Cholesterol)))
    .Select(x => new {x.GeneralName, DisplayNames = x.Nutrients.Where(a => !string.IsNullOrEmpty(a.Cholesterol)).Select(y => y.DisplayName).ToList()})
    .ToList();