返回列表1和列表2中的项目匹配的列表 [英] Return a list where items in list 1 and list 2 match

查看:218
本文介绍了返回列表1和列表2中的项目匹配的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2 List< T> List1和List2,如下所示:

列表1

  [ID:1,Name:item1] 
[ID: 2,名称:item2]
[ID:3,名称:item3]
[ID:4,名称:item4]

列表2:

  [ID:2,名称:item2] 
[ID:3,名称:item3]
[ID:5,名称:item5]
[ID:6 ,名称:item6]

如何获取仅包含对象的列表两个列表?使用上面的例子,我想返回:

  [ID:2,Name:item2] 
[ ID:3,名称:item3]

修改原始列表即可。

解决方案

  var result = list1.Intersect(list2 ).ToList(); 

是最简洁的。但请记住,它使用的默认相等比较器可能会或可能不适合您。如果没有,您可以自行提供:

  public class MyEqualityComparer:IEqualityComparer< Foo> 
{
public bool Equals(Foo x,Foo y)
{
return x.Id == y.Id;
}

public int GetHashCode(Foo obj)
{
return obj.Id.GetHashCode();



var result = list1.Intersect(list2,new MyEqualityComparer())。ToList();


Let's assume I have 2 List<T> List1 and List2 that look like this:

List 1:

[ID:1, Name:"item1"]
[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:4, Name:"item4"]

List 2:

[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:5, Name:"item5"]
[ID:6, Name:"item6"]

How can I get a list that contains only the objects that are in both lists? Using the example above, I want to return:

[ID:2, Name:"item2"]
[ID:3, Name:"item3"]

Modifying the original lists is OK. What's the best way to do this?

解决方案

  var result = list1.Intersect(list2).ToList();

Is the most succinct. However keep in mind it is using the default equality comparer which may or may not work for you. If not, you can provide your own:

    public class MyEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Foo obj)
        {
            return obj.Id.GetHashCode();
        }
    }

  var result = list1.Intersect(list2, new MyEqualityComparer()).ToList();

这篇关于返回列表1和列表2中的项目匹配的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆