基于两列LINQ不同 [英] Linq distinct based on two columns
问题描述
我已经在那里我需要获取与相同的组合独特的记录2列的要求。
我的数据会像CA(列A)和CB(B列),还有一些数据
I've a requirement where I need to fetch the unique records with same combination in 2 columns. My data would be Like CA(Column A) and CB(Column B) with some data
CA
CB
结果
1
2
结果
1
2
结果
3
4
结果
5
6
结果
2
1
结果
1
6
结果
1
6
结果
5
1
CA
CB
1
2
1
2
3
4
5
6
2
1
1
6
1
6
5
1
让我们说,我需要的价值获取记录 1
从两者应该是唯一的列。
Let's say, I need to fetch records with value 1
from both the columns which should be unique.
所以,我的最终结果应该是这样的:
So, My End result should be like :
1
2
结果
1
6
结果
5
1
在这里,我不应该获得创纪录的 2
, 1
因为该组合已存在的 1
, 2
第一条记录
Here I should not get the record 2
,1
because the combination already exists as 1
,2
in the first record.
下面是我试过的查询:
var recentchats = (from s in MessagesCollection.AsQueryable()
where (s.@from == mytopic || s.to == mytopic)
orderby s._id descending
select s).DistinctBy(x => x.from).Take(10).ToList();
我用 moreLinq
扩展 DistinctBy
,因为我需要整个记录。(对不起,坏的格式和英文!)
I've used moreLinq
extension for DistinctBy
, because I need the whole record.(sorry for bad formatting and english!!!)
在这里,我的实际需求是获取用户的最近聊天记录
推荐答案
由于其中,
已经确信这两个值中的一个是始终不变的,您可以使用 distinctBy
的总和。 (例如:1 + 2等于2 + 1)的
Since the where
has already made sure one of the two values is always the same, you can use the sum in distinctBy
. (e.g. 1 + 2 is equal to 2 + 1)
DistinctBy(x => x.from + x.to)
如果没有在那里,你可以使用最小和最大的仍然获得独特的对。
Without the where, you can use Min and Max to still get unique pairs.
DistinctBy(x => new { Min=Math.Min(x.from, x.to), Max=Math.Max(x.from, x.to) })
这篇关于基于两列LINQ不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!