Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq distinct and select new query

I have a query

var QP = (from a in QProductAllInfo select new { a.Id, a.Title, a.FullTitle}).Distinct();

Result is:

  • 1 Ivanov Ivan
  • 1 Ivanov Ivan
  • 2 Petrov Petr
  • 3 Sidorov Ivan
  • 3 Sidorov Ivan

and i need result:

  • 1 Ivanov Ivan
  • 2 Petrov Petr
  • 3 Sidorov Ivan
like image 400
alexandrovdi Avatar asked Feb 03 '23 06:02

alexandrovdi


2 Answers

Assuming that different Ids are always considered distinct you can try this.

I would probably write it in two querys. That way it is easy to debug and more readable. You can use MoreLinq.

DistinctBy

Download

var temp = from a in QProductAllInfo select new { a.Id, a.Title, a.FullTitle}.ToList();

var result = temp.DistinctBy(i => i.Id);

You can also use

Var result = temp.GroupBy(x => x.Id).Select(y => y.First());
like image 196
Sandeep Avatar answered Feb 05 '23 18:02

Sandeep


If you have duplicates in QProductAllInfo, replacing your code by this should fix your problem.

var QP = from a in QProductAllInfo.Distinct() 
         select new { a.Id, a.Title, a.FullTitle };

if this doesn't work, you can use tuples instead of anonymous types like this:

var QP = from a in QProductAllInfo
         select Tuple.Create(a.Id, a.Title, a.FullTitle);

Applying the Distinct operator on anonymous types is useless because anonymous types are always reference types that donc implement the IEquatable interface.

like image 23
Mareek Avatar answered Feb 05 '23 18:02

Mareek