C# 比较数组
大家下午好,
问题有点简单,但我整个下午都遇到问题,
我有 2 个列表:
- 整数列表(id)
- 对象列表(包含 id)
,我想比较它们,但我想获取 id没有一对(如果存在)
我想知道是否有 ac# 或 linq 方法来识别两个数组中不同的值
例如
如果我有
List<int> ids = {1,2,3,4,5}
并且
List<objectX> x = (contains id,code, and description)
我正在尝试类似
foreach (int id in ids)
{
foreach (objectX item in x)
{
if (item.id == id)
{
break;
}
else
idDiferentes.Add(id);
}
}
但就像你可以想象的那样不起作用
例如
ids= {1,2,3,4}
objectx[id] ={1,3,2}
, 当我比较它们时,id 是不同的,所以我得到了一个更大的列表,我需要的列表
我也尝试过使用 linq 外连接,但我不明白它是如何工作得很好
good afternoon everybody
the question is kinda simple but I've been having problems the whole afternoon
i have 2 lists:
- list of ints (ids)
- list of objects (that contains ids)
and i want to compare them but i want to obtain the id that doesn't have a pair (if it exists)
i was wondering if there's a c# or linq method to identify the values that are different in two arrays
example
if i have
List<int> ids = {1,2,3,4,5}
and
List<objectX> x = (contains id,code, and description)
and i was trying something like
foreach (int id in ids)
{
foreach (objectX item in x)
{
if (item.id == id)
{
break;
}
else
idDiferentes.Add(id);
}
}
but like you can imagine it doesn't work
for example
ids= {1,2,3,4}
objectx[id] ={1,3,2}
the ids are different when i compare them so i get a bigger list that the one i need
i also tried with an linq outer join but i don't understand how it works pretty well
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您所追求的是 Except 扩展方法。它为您提供两个序列之间的设定差异。
所以你可以做这样的事情(伪c#代码):
What you are after is the Except extension method. It gives you the set difference between two sequences.
So you can do something like this (pseudo c#-code):
Linq 设置操作:
就这样。
Linq Set Operations:
There you go.
作为 LINQ 的替代方案(尽管 LINQ 可能是正确的答案),如果您的所有 id 都是唯一的,您可以使用
Contains()
方法,例如:As an alternative to LINQ (although LINQ is probably the right answer here), if all your ids are unique you may be able to use the
Contains()
method, for example:使用标志更容易,例如:
It is easier to use a flag, e.g.: