2016-09-23 114 views
4

我有一个像使用LINQ选择列表

 { 
     "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" 

    } 

名单,我需要找到具有胆固醇空字符串值项的General_name以外的项目。

我试图使用LINQ lambda表达式作为

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

我的问题是如何从这种情况

回答

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

这将让你所有的GeneralName值,其中的列表得到的总称包含Nutrients集合包含一个非空值的胆固醇。那是你在找什么?


编辑:

有没有一种方法可以让我得到这些项目的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(); 
+0

是的,我忘了布尔选项。感谢 – Mithun

+0

@Mithun - 很高兴为你工作。请考虑接受答案(请参阅[如何接受所​​有答案](http://meta.stackexchange.com/a/5235)),一旦过了15分钟。 – Igor

+0

有没有办法让我可以得到这些物品的display_name? – Mithun

0

以下是使用SelectMany你的原代码的修改来实现相同的:

var elements = items.SelectMany(i => 
           i.nutrients.Select(n => new { n, i.CountryOfOrigin, i.GeneralName} 
          ).Where(h => !string.IsNullOrEmpty(h.n.cholesterol) 
          ).GroupBy(g => new { g.CountryOfOrigin, g.GeneralName } 
          ).Select(s => new Item { 
                 GeneralName = s.Key.GeneralName, 
                 CountryOfOrigin = s.Key.CountryOfOrigin, 
                 nutrients = s.Select(v => v.n).ToList() 
                } 
          ); 

说明:

  • 拼合使用选择很多
  • 过滤器空Chloestrol项目
  • 的GroupBy使用GeneralNameCountryofOrigin,这是个别项目
  • 碎石GroupBy结果Items集合,用必要的值
  • 取任何财产从Result项目集合