结合两个条件的实体列表



说我有一个定义为

的类
class Object
{
    public int ID { get;set; }
    public string Property { get; set; }
    public override bool Equals(object obj)
    {
        Object Item = obj as Object;
        return Item.ID == this.ID;
    }
    public override int GetHashCode()
    {
        int hash = 13;
        hash = (hash * 7) + ID.GetHashCode();
        return hash;       
    }
}

和两个列表,如下定义:

List<Object> List1;
List<Object> List2;

这两个列表包含ID字段可能相同的对象,但是Property字段可能也可能不会。我想与List1中包含的所有对象以及List2, with the condition that属性中包含的所有对象的结果field must be set to" 1" if it is set to" 1"``在任何这些列表中。结果必须包含不同的值(不同的ID)。

例如,如果我们有两个这样的列表:

List1 
-----  
ID = 0, Property = "1"
ID = 1, Property = ""
ID = 2, Property = "1"
ID = 3, Property = ""
List2
-----
ID = 1, Property = "1"
ID = 2, Property = ""
ID = 3, Property = ""

我需要一个结果才能这样:

Result
-------
ID = 0, Property = "1"
ID = 1, Property = "1"
ID = 2, Property = "1"
ID = 3, Property = "" 

目前的工作原理:

var Result = List1.Except(List2).Concat(List2.Except(List1));
var Intersection = List1.Intersect(List2).ToList();
Intersection.ForEach(x => {
    x.Property = List1.Single(y => y.ID == x.ID).Property == "1" ? "1" : List2.Single(y => y.ID == x.ID).Property == "1" ? "1" : "";
});
Result = Result.Concat(Intersection);

...但是foreach非常慢。有人可以提出更快的方式吗?

var result = List1.Concat(List2)
                  .GroupBy(o => o.ID)
                  .Select(g => new Object() { 
                                   ID=g.Key,
                                   Property=g.Any(o=>o.Property=="1")?"1":""
                   })
                  .ToList();
var result = List1.Concat(List2)
        .OrderByDescending(o => o.Property)
        .GroupBy(g => o.ID)
        .Select(g => g.First())
        .ToList();

相关内容

  • 没有找到相关文章

最新更新