linq distinct and select new query
36,727
Solution 1
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
.
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());
Solution 2
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.
Comments
-
alexandrovdi about 4 years
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
-
alexandrovdi about 12 yearsit is helped but i can't do code like this datagridview.datasource = result;
-
Sandeep about 12 yearsYou can not assign an Ienumerable to a Datasource. Please google on how to assign the Ienumerable to Datasource. I am not good at ASP.net
-
alexandrovdi about 12 yearsin real i need select more then 8 items. and in the end i need do next: datagridview.datasource=QP;
-
Sandeep about 12 yearsIt is not mine dude. It is Jon Skeets Brain child. I am just a user of it.