首页 > 解决方案 > 从另一个列表中过滤 IEnumerable

问题描述

我有一个IEnumerable<int>with items1, 5, 10, 85, 96和另一个 IEnumerable<Hw> lstHwHwclass 有 property HwID

我想过滤以获取( )IEnumerable<int>中不存在的值。IEnumerable<Hw>HwID

所以输出应该给我:1, 5, 85

我们怎么能做到这一点?

标签: c#listgenericsfilterienumerable

解决方案


如果我正确地阅读此内容,您希望从 中获取所有整数,这些整数在另一个列表中List<int>没有对应的匹配项。HwHWId

如果是这样,您可以使用这些System.Linq方法Where过滤掉其中All的项目lstHw没有HwID匹配的项目:

var ints = new List<int> {1, 5, 10, 85, 96};
var lstHw = new List<Hw> {new Hw {HwID = 10}, new Hw {HwID = 96}};

var results = ints.Where(i => lstHw.All(hw => hw.HwID != i));

更新
根据您在评论部分的代码,您似乎实际上有两个List<int>集合(嗯,一个是 a List<uint>)。这是你的评论:

IEnumerable<Int32> hwids = scopedZcat.GetProductsByFamily(auto.PlatformID);
IEnumerable<uint> selectedHwId = lstZcatCases
    .Where(c => c.CaseID != auto.CaseID)
    .Select(i => i.HWID)
    .ToList(); 

// Now I want the hwids which are not there in selectedHwid

如果是这种情况,那么这应该可以解决问题:

// Note that we have to cast a `uint` to an `int`
var results = hwids.Except(selectedHwId.Select(id => (int)id));

推荐阅读