C#Linq-获取包含整数列表的所有元素

时间:2018-12-19 09:43:25

标签: c# linq

我有一个对象列表,其中包含每个对象内部的类型列表,类似以下内容:

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 }

2 个答案:

答案 0 :(得分:2)

您必须交替更改LINQ查询中的两个列表:

var objectsAdmited = allObjects.Where(b => typesAdmited.All(t => b.Types.Contains(t)));

答案 1 :(得分:1)

您可以使用Linq解决此问题。看到中间的小代码块-其余的都是样板,使其成为Minimal complete verifyabe answer

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