2013-01-31 46 views
2

我试图使用Linq Union向结果中添加更多记录,但Union不起作用。也许有人可以指引我正确的方向。Linq Union不工作

 public class ProductView 
        { 
         public int Id { get; set; } 
         public bool Active { get; set; } 
         public string Name { get; set; } 
         public int ProductTypeId { get; set; } 
         public int UserCount { get; set; } 

     } 

void Main() 
{ 


var product = Products.Select(p => new ProductView 
    { 
     Id = p.Id, 
     Active = p.Active, 
     Name = p.Name, 
     ProductTypeId = p.ProductTypeId, 
     UserCount = 1 
    }).ToList(); 


    //The new item is not jointed to the result above 
    product.Union(new[] { 
      new ProductView 
      { 
      Id = 9999, 
      Active = true, 
      Name = "Test", 
      ProductTypeId=0, 
      } 
     }); 


product.Dump();           
} 
+0

在'ProductView'中覆盖'Equals'和'GetHashCode'。 –

回答

3

您需要存储的输出:

var product2 = product.Union(new[] { 
    new ProductView 
    { 
    Id = 9999, 
    Active = true, 
    Name = "Test", 
    ProductTypeId=0, 
    } 
}); 

product2.Dump(); 

除此之外,压倒一切的Equals的行为将是有益的 - 因为你可能希望只使用ID字段检查平等?


例如,如果不重写Equals的行为,那么你会得到对象引用等于这样的:

void Main() 
{ 

    var list = new List<Foo>() 
    { 
    new Foo() { Id = 1}, 
    new Foo() { Id = 2}, 
    new Foo() { Id = 3}, 
    }; 

    var list2 = new List<Foo>() 
    { 
    new Foo() { Id = 1}, 
    new Foo() { Id = 2}, 
    new Foo() { Id = 3}, 
    }; 

    var query = list.Union(list2); 

    query.Dump(); 

} 

// Define other methods and classes here 

public class Foo 
{ 
public int Id {get;set;} 
} 

产生六个项目!

但是,如果你改变美孚到:

public class Foo 
{ 
    public int Id {get;set;} 

    public override bool Equals(object obj) 
    { 
    if (obj == null || !(obj is Foo)) return false; 
    var foo= (Foo)obj; 
    return this.Id == foo.Id; 
    } 

    public override int GetHashCode() 
    { 
     return this.Id.GetHashCode(); 
    }  
} 

,那么你将获得3项 - 这可能是你期待什么。

+0

这工作正常,为什么有人投票答案? – Tomas

+0

不知道为什么 - 但它是正确的答案请参阅http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b上的优秀示例:( – Stuart

+0

是的 - 看起来像某人正在投票回答很多答案...随意标记第一个帮助正确的:) – Stuart

1

你需要重写EqualsGetHashCodeProductView,如果你想以有意义的方式使用Union(除refence比较)。

public class ProductView 
{ 
    public int Id { get; set; } 
    public bool Active { get; set; } 
    public string Name { get; set; } 
    public int ProductTypeId { get; set; } 
    public int UserCount { get; set; } 

    public override bool Equals(object obj) 
    { 
     if (obj == null || !(obj is ProductView)) return false; 
     ProductView pv2 = (ProductView)obj; 
     return this.Id == pv2.Id; 
    } 

    public override int GetHashCode() 
    { 
     return this.Id.GetHashCode(); 
    } 
} 

你也可以用类似的方式实施IEqualityComparer<ProductView>并将其用于this overload of Union