Thursday 15 April 2010

c# - Linq group query gives wrong results -


I have a problem in executing a Linq query with the group in the C # project:

  public class stock {public string name {get; Set;} public list & lt; Int & gt; Value {receive; Set;} public float value {receives; Set;}} // archive archive list & lt; Stock & gt; Stock = new list & lt; Stock & gt; () {New Stock () {name = "Prod 1", value = new list & lt; Int & gt; {1, 2, 3, 0}, value = 5.0f, new stock () {name = "prod1", value = new list & lt; Int & gt; {1, 2, 3, 0}, value = 5.0f, new stock () {name = "product 11 ", value = new list & lt; Int & gt; {1, 0, 3, 1}, value = 8.0F, new stock () {name = "product 11 ", value = new list & lt; Int & gt; {1, 0, 3, 1}, value = 8.0F, new stock () {name = "prod18", value = new list & lt; Int & gt; {0, 0, 4, 1}, value = 4.5 f, new stock () {name = "prod20", value = new list & lt; Int & gt; {4, 0, 0, 2}, value = 9 9f, new stock () {name = "prod 20", value = new list & lt; Int & gt; {4, 0, 2}, value = 9 9f, new stock () {name = "prod 29", value = new list & lt; Int & gt; {2, 1, 0, 1}, value = 7.2f,}; Var query = stock. Group by (x = x = x, (x, g) => new {count = g., Number (), value = x}). ToList ();  

This query returns the wrong group results.

GroupBy to create the group, by which object you GetHashCode and equal should be override, or you need to provide an appropriate parity with groupb . your stock not override GetHashCode / equal , and your GroupBy query custom parity Does not use, so you get unexpected results.

Providing an appropriate override will fix this problem:

  public class stock {public string name {get; Set;} public list & lt; Int & gt; Value {receive; Set;} public float value {receives; Set;} Public override baul par (object obj) {if (obj == this) come back true; Var other = obj as stock; If returned (other == empty) wrong; Return name Ecloss (other name) & amp; Amp; Price == Other Price & amp; Amp; Values.SequenceEqual (other.Values); } Public override intoshosh () {return name.gethashcode () + price.gethashcode () + value SIM (); }}  


No comments:

Post a Comment