使用Linq选择列表外的项

4

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"

     }

我需要找出那些胆固醇为空字符串的项目的通用名称。

我尝试使用LINQ Lambda表达式:

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

我的问题是如何从这个条件中获取通用名称

1个回答

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

这将为您提供一个包含胆固醇非空值的营养素集合的所有GeneralName值列表。这是您要寻找的吗?


编辑:

有没有办法也获取这些项目的display_name?

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();

是的,我忘记了bool选项。谢谢。 - Mithun
@Mithun - 很高兴它对你有用。请在15分钟时间到期后考虑接受答案(请参阅如何接受SO答案)。 - Igor
有没有办法也获取这些项目的 display_name? - Mithun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接