How can I do a SELECT
where I get the DISTINCT
result based on the FromLinkID
AND ToLinkID
together?
If I have a List
with the following data, how could I get what I am after in LINQ?
How can I do a SELECT
where I get the DISTINCT
result based on the FromLinkID
AND ToLinkID
together?
If I have a List
with the following data, how could I get what I am after in LINQ?
SELECT DISTINCT FromLinkId, ToLinkId
FROM mytable
To select one record per (FromLinkId, ToLinkId)
(that with the least id
), assuming SQL Server
:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY FromLinkId, ToLinkId ORDER BY id) AS rn
FROM mytable
) q
WHERE rn = 1
try this:
Select Distinct FromLinkId LinkId From MyTable
Union
Select Distinct ToLinkId LinkId From MyTable
SELECT Name, FromLinkId, ToLinkId FROM MyTable GROUP BY FromLinkId, ToLinkId -- if there are more than one record with the same (FromLinkId, ToLinkId) pair, only one of them is displayed.
You can do something like:
SELECT MAX(ID), MAX(Name), FromLinkID, ToLinkID FROM MyTable
GROUP BY FromLinkID, ToLinkID
Or even:
SELECT t.* FROM
(SELECT MAX(ID) as MaxID, FromLinkID, ToLinkID FROM MyTable
GROUP BY FromLinkID, ToLinkID) d
LEFT JOIN MyTable t ON d.MaxID=t.ID
LINQ solution:
List<MyObj> distinctResults = allResults
.GroupBy(p => new {p.FromLinkID, p.ToLinkID} )
.Select(g => g.First())
.ToList();
hope it helps someone.
List distinctResults = allResults .Select(p => new {p.FromLinkID, p.ToLinkID} ) .Distinct() .ToList();