【问题标题】:compare two lists of differtent types using linq使用 linq 比较两个不同类型的列表
【发布时间】:2014-01-10 23:27:57
【问题描述】:

我正在寻找一种方法来比较两个列表中的对象。列表中的对象有两种不同的类型,但共享一个键值。例如

public class A
{
    public string PropA1 {get;set;}
    public string PropA2 {get;set;}
    public string Key {get;set;}
}

public class B
{
    public string PropB1 {get;set;}
    public string PropB2 {get;set;}
    public string Key {get;set;}
}

var listA = new List<A>(...);
var listB = new List<B>(...);

获取类型 A 的对象列表(其中键不存在于 listB 中)、类型 B 的对象列表(其中键不存在于 listA 中)以及连接列表的最快方法是什么具有匹配键的对象?我已经设法使用 Linq 创建了加入列表:

var joinedList = listA.Join(listB,
    outerkey => outerkey.Key,
    innerkey => innerkey.Key,
    (a, b) => new C
    {
        A = a,
        B = b
    }).ToList();

但这当然只包含匹配的对象。有没有办法获取其他列表?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    获取B中没有键的A的集合可以如下完成

    var hashSet = new HashSet<String>(bList.Select(x => x.Key));
    var diff = aList.Where(x => !hashSet.Contains(x.Key));
    

    做相反的事情就像切换列表一样简单。或者我们可以将其抽象为一个函数,如下所示

    IEnumerable<T1> Diff<T1, T2>(
      IEnumerable<T1> source, 
      IEnumerable<T2> test,
      Func<T1, string> getSourceKey,
      Func<T2, string> getTestKey) {
    
      var hashSet = new HashSet<string>(test.Select(getTestKey));
      return source.Where(x => !hashSet.Contains(getSourceKey(x));
    }
    
    // A where not key in B 
    Diff(aList, bList, a => a.Key, b => b.Key);
    
    // B where not key in A
    Diff(bList, aList, b => b.Key, a => a.Key);
    

    【讨论】:

    • 太棒了,正是我需要的!
    猜你喜欢
    • 2019-04-22
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    相关资源
    最近更新 更多