为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕村225694 2022-06-18 17:32:58
我有一个对象列表,每个对象内部都有一个类型列表,类似于这样: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 来获取所有承认类型的对象时,我会得到任何结果。我正在尝试这个: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 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

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

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



查看完整回答
反对 回复 2022-06-18
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

您可以使用 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


查看完整回答
反对 回复 2022-06-18
  • 2 回答
  • 0 关注
  • 192 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信