[英]c# Linq - Get all elements that contains a list of integers
我有一個對象列表,每個對象內部都有類型列表,類似這樣的東西:
public class ExampleObject
{
public int Id {get; set;}
public IEnumerable <int> Types {get;set;}
}
例如:
var typesAdmited = new List<int> { 13, 11, 67, 226, 82, 1, 66 };
在對象列表中,我有一個像這樣的對象:
Object.Id = 288;
Object.Types = new List<int> { 94, 13, 11, 67, 254, 256, 226, 82, 1, 66, 497, 21};
但是,當我使用linq來獲取所有具有允許的類型的Object時,我會得到任何結果。 我正在嘗試:
var objectsAdmited = objects.Where(b => b.Types.All(t => typesAdmited.Contains(t)));
例:
var typesAdmited = new List<int> { 13, 11, 67, 226, 82, 1, 66 };
var objectNotAdmited = new ExampleObeject {Id = 1, Types = new List<int> {13,11}};
var objectAdmited = new ExampleObject {Id = 288, Types = new List<int> { 94, 13, 11, 67, 254, 256, 226, 82, 1, 66, 497, 21}};
var allObjects = new List<ExampleObject> { objectNotAdmited, objectAdmited };
var objectsAdmited = allObjects.Where(b => b.Types.All(t => typesAdmited.Contains(t)));
我得到:
objectsAdmited = { }
它應該是:
objectsAdmited = { objectAdmited }
您必須交替更改LINQ查詢中的兩個列表:
var objectsAdmited = allObjects.Where(b => typesAdmited.All(t => b.Types.Contains(t)));
您可以使用Linq解決此問題。 看到中間的小代碼塊-其余的部分使它成為最小的完整驗證模板 :
using System;
using System.Collections.Generic;
using System.Linq;
public class ExampleObject
{
public int Id { get; set; }
public IEnumerable<int> Types { get; set; }
}
class Program
{
static void Main (string [] args)
{
var obs = new List<ExampleObject>
{
new ExampleObject
{
Id=1,
Types=new List<int> { 94, 13, 11, 67, 254, 256, 226, 82, 1, 66, 497, 21 }
},
new ExampleObject
{
Id=288,
Types=new List<int> { 94, 13, 11, 67, 256, 226, 82, 1, 66, 497, 21 }
},
};
var must_support = new List<int>{11, 67, 254, 256, 226, 82, }; // only Id 1 fits
var must_support2 = new List<int>{11, 67, 256, 226, 82, }; // both fit
// this is the actual check: see for all objects in obs
// if all values of must_support are in the Types - Listing
var supports = obs.Where(o => must_support.All(i => o.Types.Contains(i)));
var supports2 = obs.Where(o => must_support2.All(i => o.Types.Contains(i)));
Console.WriteLine ("new List<int>{11, 67, 254, 256, 226, 82, };");
foreach (var o in supports)
Console.WriteLine (o.Id);
Console.WriteLine ("new List<int>{11, 67, 256, 226, 82, };");
foreach (var o in supports2)
Console.WriteLine (o.Id);
Console.ReadLine ();
}
}
輸出:
new List<int>{11, 67, 254, 256, 226, 82, };
1
new List<int>{11, 67, 256, 226, 82, };
1
288
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.