Linq to SQL/过滤重复项 [英] Linq to SQL / filter duplicates
问题描述
我在我的 sql server 2012 中有一个视图,有几个重复项,我想按最新对它们进行排序并过滤所有其他视图 - 谁能帮我?
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?
我在 SQL Server 2012 中的视图:
My viewin my SQL Server 2012:
GUID(作为主键)、数字、日期时间和名称
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
+-------+--------+--------------------------------+-----
如果号码相同,则名称每次都相同.例如编号 1234567 始终是名称 1.
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
所以结果应该是:
+-----+----------+--------------------------------+-----
| 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
+-------+--------+--------------------------------+-----
我怎样才能在 Linq 中做到这一点?由于 guid 和日期时间,Distinct"不起作用
How can i do this in Linq? "Distinct" is not working because of the guid and the datetime
推荐答案
var res = list.GroupBy(c => c.name).Select(group => group.OrderBy( c1 => c1.datetime).First()).ToList();
只要 datetime 存储为 DateTime
的实例,而不是字符串,这应该可以工作.
This should work as long as datetime is stored as an instance of DateTime
, instead of string.
这篇关于Linq to SQL/过滤重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!