Anthony
Anthony

Reputation: 923

c# linq returns duplicate data

I have a this linq query:

var fling = (from b in flowering.FlowerViews
                     where ((!string.IsNullOrEmpty(flow_name)) && b.FLOWER_NAME == flow_name) || flow_name==""
                     where ((!string.IsNullOrEmpty(color_name)) && b.COLOR_NAME == color_name) || color_name == ""
                     where ((!string.IsNullOrEmpty(size)) && b.FLOWER_SIZE == size) || size==""
                     where ((low_price!=0) && low_price<= b.FLOWER_PRICE) || low_price==0
                     where ((high_price!=0) && high_price >= b.FLOWER_PRICE)  || high_price==0
                     orderby b.COLOR_NAME
                     select new { b.FLOWER_NAME, b.COLOR_NAME, b.FLOWER_SIZE, b.FLOWER_PRICE, b.CHAR_DESC});

my where clauses work for me but when I run a for each loop over the returned values there is duplicate data because b.CHAR_DESC has 3 values to it where all the other return data only have one. I am wondering if there is a way to get the 3 values assigned to b.CHAR_DESC into a structure that does not cause duplicate b.Flower_name's to show up

Upvotes: 0

Views: 526

Answers (2)

Bala R
Bala R

Reputation: 109027

Based on this post you should be able to call Distinct() for the anonymous type

var list = fling.Distinct().ToList();

And the compiler will take care of GetHashCode() and Equals() for the anonymous type based on attribute values.

Upvotes: 5

Josh M.
Josh M.

Reputation: 27831

Add .Distinct() at the end of your select clause, after the final parenthesis.

Upvotes: 5

Related Questions