联合比较器

Union with Comparer

我有一个项目列表,我正在尝试重新记录不同的项目,

有的记录没有Id(0),有的有Id,有Id的可以取吗?

void Main() {

var a = new Skill {Id =0, Name="test"};
var b = new Skill {Id =0, Name="test"};
var c = new Skill {Id= 1, Name="test" }; // masterlist skill
var listA = new List<Skill> { a, b };
var listB = new List<Skill> { c };

var result = listA.Union(listB, new SkillComparer());

result.Dump();
} 

public class SkillComparer : IEqualityComparer<Skill>
{

#region IEqualityComparer<Skill> Members

public bool Equals(Skill skill, Skill skillToCompare)
{
    return skill.Name == skillToCompare.Name;
}

public int GetHashCode(Skill obj)
{
    return obj.Name.GetHashCode();
}

#endregion
}

 public class Skill {
 public int Id {get;set;}
 public string Name {get;set;}

结果

ID:0 | Name: Test

有没有办法 returns materlist 的 id?

ID:1 | Name: Test

使用 linq:

var result = listA.Concat(listB).OrderByDescending(s => s.Id).Distinct(new SkillComparer());

这会产生一个不同的技能列表,每个技能都包含其名称的最大 ID。

var a = new Skill {Id =0, Name="test"};
var b = new Skill {Id =2, Name="test"};
var c = new Skill {Id= 1, Name="test" };
var d = new Skill { Id = 3, Name = "foo" };
var e = new Skill { Id = 0, Name = "foo" };

var listA = new List<Skill> { a, b };
var listB = new List<Skill> { c, d, e };

var result = listA.Concat(listB).OrderByDescending(s => s.Id).Distinct(new SkillComparer());

foreach (var skill in result)
{
    Console.WriteLine(string.Format("{0}: {1}", skill.Name, skill.Id));
}

结果:

foo: 3
test: 2

还有更有效的方法,但据我所知:

listA.AddRange(listB).Where(o => o.Name == desiredName).Max(o => o.Id);