问题
i have a view in my sql server 2012 with a couple of duplicates and i want to sort them by the newest and filter all others - can anyone help me?
My viewin my SQL Server 2012:
GUID (as primary key), number, datetime and name
+-----+----------+--------------------------------+-----
| guid | number| datetime | name
+-----+----------+--------------------------------+------
| b105..| 1234567|2014-07-07T16:32:20.854+02:00:00|Name1
| s1b5..| 1111222|2014-07-06T16:30:21.854+02:00:00|Name2
| b17a..| 1234567|2014-07-06T15:22:17.854+02:00:00|Name1
| f205..| 1233333|2014-07-07T17:40:20.854+02:00:00|Name3
| b11t..| 1233333|2014-07-04T11:12:15.854+02:00:00|Name3
| rt85..| 1111222|2014-07-07T21:55:52.854+02:00:00|Name2
+-------+--------+--------------------------------+-----
the name is every time the same if the number is the same. for e.g. number 1234567 is always name 1.
I want to filter my table that i have only the newest number without duplicates
so the result should be:
+-----+----------+--------------------------------+-----
| guid | number| datetime | name
+-----+----------+--------------------------------+------
| b105..| 1234567|2014-07-07T16:32:20.854+02:00:00|Name1
| f205..| 1233333|2014-07-07T17:40:20.854+02:00:00|Name3
| rt85..| 1111222|2014-07-07T21:55:52.854+02:00:00|Name2
+-------+--------+--------------------------------+-----
How can i do this in Linq? "Distinct" is not working because of the guid and the datetime
回答1:
var res = list.GroupBy(c => c.name).Select(group => group.OrderBy( c1 => c1.datetime).First()).ToList();
This should work as long as datetime is stored as an instance of DateTime
, instead of string.
回答2:
You can do it by grouping your elements by 2 columns. (number and name). Then access the grouped data. You can do it somehow like that:
var query =
from col in viewData
group col by new
{
col.name,
col.number,
} into groupedCol
select new viewData()
{
number = groupedCol.Key.number,
name = groupedCol.Key.name,
datetime = groupedCol.OrderBy( dateCol => dateCol.datetime).First()
};
来源:https://stackoverflow.com/questions/24790715/linq-to-sql-filter-duplicates