2

我试图弄清楚如何最好地将两个List<T>与生成的新对象进行比较和合并,以List<T>比较每个对象中的多个属性。

class Account
{
    public Account() { }
    public string ID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

List<Account> Mine = new List<Account>();
List<Account> Yours = new List<Account>();
List<Account> Ours = new List<Account>();

Account m1 = new Account(){ ID = null, Name = "C_First", Value = "joe" };
Account m2 = new Account(){ ID = null, Name = "C_Last", Value = "bloggs" };
Account m3 = new Account(){ ID = null, Name = "C_Car", Value = "ford" };

Mine.Add(m1);
Mine.Add(m2);
Mine.Add(m3);

Account y1 = new Account(){ ID = "1", Name = "C_First", Value = "john" };
Account y2 = new Account(){ ID = "2", Name = "C_Last", Value = "public" };

Yours.Add(y1);
Yours.Add(y2);

结果List<Account> Ours将具有以下List<Account>对象:

{ ID = "1", Name = "C_First", Value = "joe" };
{ ID = "2", Name = "C_Last", Value = "bloggs" };
{ ID = null, Name = "C_Car", Value = "ford" };

我需要弄清楚如何最好地比较两个List<Account>对象之间的 ID 和 Value 属性,其中List<Account> YoursID 优先于List<Account> Mine并且List<Account> MineValue 优先于List<Account> Yours任何未List<Account> Yours添加的对象。

我尝试了以下方法:

Ours = Mine.Except(Yours).ToList();

这导致List<Ours>为空。

我已经阅读了这篇文章两个列表之间的区别,其中 Jon Skeet 提到使用自定义IEqualityComparer<T>来做我需要的事情,但我坚持如何创建一个IEqualityComparer<T>比较多个属性值的比较。

4

3 回答 3

3

不确定它是否可以在“pue”LINQ 中完成,但一些程序代码可以解决问题:

var dict = Yours.ToDictionary(y => y.Name);
foreach (var m in Mine) {
    Account y;
    if (dict.TryGetValue(m.Name, out y))
        Ours.Add(new Account { ID = y.ID, Name = m.Name, Value = m.Value });
    else
        Ours.Add(m);
}

之后,打印Ours...

foreach (var o in Ours)
    Console.WriteLine("{0}\t{1}\t{2}", o.ID, o.Name, o.Value);

...给出以下结果:

1       C_First joe
2       C_Last  bloggs
        C_Car   ford
于 2013-10-31T05:51:57.323 回答
0

尝试这个:

var index = Mine.ToDictionary(x => x.Name);

foreach(var account in Yours)
{
    if(index.ContainsKey(account.Name))
    {
        var item = index[account.Name]; 
        if(item.ID == null)
            item.ID = account.ID;
    }
    index.Add(account.Name, account);
}

Ours = index.Values.ToList();
于 2013-10-31T05:47:52.543 回答
0

试试这个 IEqualityComparer 的代码:

public class D : IEqualityComparer<Account>
{
    public bool Equals(Account x, Account y)
    {
        return x.ID == y.ID && x.Value==y.Value;
    }

    public int GetHashCode(Account obj)
    {
        return obj.ID.GetHashCode() ^ obj.Value.GetHashCode();
    }
}

像这样使用: Ours = Mine.Except(Yours, new D()).ToList();

于 2013-10-31T06:02:09.980 回答