使用 LINQ 选择 2 个列表之间的匹配结果

我有 2 个列表:


清单 1:


[

{

"TPN": "AL M",

"IL": [

  {

    "PIN": 1502103214,

    "Suffix": null

  }

]

},

{

"TPN": "ABC",

"IL": [

  {

    "PIN": 6509507561,

    "Suffix": null

  },

  {

    "PIN": 1234056789,

    "Suffix": null

  }


]

},

{

"TPN": "XYZ",

"IL": [

  {

    "PIN": 7507668878,

    "Suffix": null

  }

]

}

]

清单 2:


List<decimal> list2 = new List<decimal>(){ 6509507561, 7507668878 }

我想根据列表 2 的值过滤列表 1。所以我的最终名单应该是


[

  {

    "TPN": "ABC",

    "IL": [

       {

         "PIN": 6509507561,

         "Suffix": null

       }

     ]

  },

  {

    "TPN": "XYZ",

    "IL": [

       {

        "PIN": 7507668878,

        "Suffix": null

       }

     ]

   }

]

我使用的 LINQ 查询是:


var indInfoTemp = list1.Where(ind => ind.IL.All(x => list2.Any(y => y == x.PIN)))

                       .ToList();

谁能告诉我这个查询有什么问题。


料青山看我应如是
浏览 155回答 3
3回答

慕尼黑的夜晚无繁华

您可以检查是否IL包含 PIN,然后IL使用按 PIN 的选择进行过滤。var indInfoTemp = list1.Where(ind => ind.IL.Any(il => list2.Contains(il.PIN)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Select(ind => new {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ind.TPN,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;IL = ind.IL.Where(il => list2.Contains(il.PIN))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToList()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToList();

慕桂英3389331

你可以使用这样的扩展:public&nbsp;static&nbsp;class&nbsp;Extensions{ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;static&nbsp;bool&nbsp;In<T>(T&nbsp;input,&nbsp;params&nbsp;T[]&nbsp;list)&nbsp;=>&nbsp;list.Any(item&nbsp;=>&nbsp;item.Equals(input)); }并像这样使用它:var&nbsp;indInfoTemp&nbsp;=&nbsp;list1.Where(ind&nbsp;=>&nbsp;ind.IL.PIN.In(list2.ToArray())).ToList();

一只斗牛犬

任何回报,bool所以你正在使用那个 bool 的 all 函数如果您只想选择 list2 中包含的 list 1 的值,请.contains像这样使用:indInfoTemp&nbsp;=&nbsp;list1.Where(ind&nbsp;=>&nbsp;list2.Contains(ind.IL[0].PIN)).ToList();
打开App,查看更多内容
随时随地看视频慕课网APP