【问题标题】:Combine two lists of entities with a condition将两个实体列表与条件相结合
【发布时间】:2012-10-17 23:56:21
【问题描述】:

假设我有一个定义为

的类
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 thatPropertyfield must be set to"1"if it is set to"1"` 中包含的所有对象的结果。结果必须包含不同的值(不同的 ID)。

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

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 非常慢。有人可以提出更快的方法吗?

【问题讨论】:

    标签: c# linq list intersect except


    【解决方案1】:
    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();
    

    【讨论】:

      【解决方案2】:
      var result = List1.Concat(List2)
              .OrderByDescending(o => o.Property)
              .GroupBy(g => o.ID)
              .Select(g => g.First())
              .ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2014-08-02
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        相关资源
        最近更新 更多