C#将2个列表与字符串数组属性进行比较

时间:2015-06-20 08:24:45

标签: c# arrays list properties compare

我有一个具有List<String>属性的类来保存一个或多个字符串ID的动态列表。

public class FieldCompareItem
{
    public List<string> Fields = new List<string>();

    public FieldCompareItem(string[] fields)
    {
        for (int i = 0; i < fields.Count(); i++)

            Fields.Add(fields[i]);
        }
    }
}

我试图比较2个列表,看看字符串数组是否匹配,但它不起作用。基本上,我想进行A / B比较以获得仅存在于A,B和两者中的项目,如下所示:

var listA = new List<FieldCompareItem>
        {
            new FieldCompareItem(new[] {"a1"}),
            new FieldCompareItem(new[] {"a2"}),
            new FieldCompareItem(new[] {"a3","001"})
        };

var listB = new List<FieldCompareItem>
        {
            new FieldCompareItem(new[] {"a2"}),
            new FieldCompareItem(new[] {"a3"}),
            new FieldCompareItem(new[] {"a3","001"}),
            new FieldCompareItem(new[] {"a4"}),
            new FieldCompareItem(new[] {"a5"})
        };

//exists in A only
var aOnly = listA.Except(listB).ToList();
//expect a1,a3

//exists in B only
var bOnly = listB.Except(listA).ToList(); 
//expect a4,a5

//exists in both - this may be used for update A>B or B>A
var inBoth = ?????
//expect a2

因为它们是数组属性中的值,所以它似乎无法按条件查找。任何帮助赞赏

1 个答案:

答案 0 :(得分:0)

首先创建一个比较器:

public class FieldCompareItemComparer: IEqualityComparer<FieldCompareItem>
{
  public bool Equals(FieldCompareItem x, FieldCompareItem y)
  {
    var result = x.Fields.SequenceEqual(y.Fields);
    return result;
  }

  public int GetHashCode(FieldCompareItem obj)
  {
    return String.Concat(obj.Fields).GetHashCode();
  }
}

然后使用它如下:

var comparer = new FieldCompareItemComparer();

// exists in A only
var aOnly = listA.Except(listB, comparer).ToList();

// exists in B only
var bOnly = listB.Except(listA, comparer).ToList();

// exists in both
var inBoth = listA.Intersect(listB, comparer).ToList();