3

I wonder why I am not able to find this error on stackoverflow. In Linq to SQL, i am selecting an anonymous object like

var something = from a in .....
    ......
    ......
    select new 
    { 
        myParameter = a.Something 
        myListParameter = (from b in ........
                           select b)
    }
.
.
.
.
something = something.Distinct(); //This is giving error

In selecting anonymous type object above, in one of the properties I am selecting another list. I guess this might be causing the issue. I wonder if there is a workaround.

Tim
  • 5,435
  • 7
  • 42
  • 62
Taha Rehman Siddiqui
  • 2,441
  • 5
  • 32
  • 58

2 Answers2

10

It may be because your query is returning more than one result,

try using

something = something.Distinct().ToList();

You can use a workaround if applicable to your requirements .

something = something.GroupBy(x => x.PropertyToCompare).Select(x => x.First());
Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
3

there is no way to Distinct() an anonymous type as each object will be held in different memory space, and therefore not equatable.

You will likely need to implement IEquatable to use Distinct() as per this response: Distinct not working with LINQ to Objects

Community
  • 1
  • 1
  • but that is Linq to Objects, I know that implementing an IEquatable will solve the problem, but I can't define one for Anonymous types or can I? – Taha Rehman Siddiqui Dec 12 '13 at 10:41
  • Correct - pretty much the only way then is to group then first(), which technically isn't a distinct, rather the first of each group. If you have data that is different in non-compared fields, then your results will differ. – Bradley Smith Dec 18 '13 at 21:31
  • the answer was sufficiently workable in my case, we have primary keys in our table and I just grouped the data on that field. – Taha Rehman Siddiqui Dec 20 '13 at 09:03