如何使用 Linq to select 匿名 IEnumerable 集合中的项目
How to use Linq to select items from a anonymous IEnumerable collection
我有 2 个包含字符和字符计数的 IEnumerable 集合(即 s1{Key = 'a' Count='5'} 和 s2{Key='a' Count = '4'})
我想使用 Linq 查询执行以下操作:
如果项目在两个集合中,我只想要集合中计数较高的项目,即 Count=5 from s1
如果该项目仅在一个集合中,则我们使用该项目(不能使用 Distinct,因为它说 IEnumerable Anonymous 不包含 Distinct)
如果项目在两个集合中但它们的数量相等,则我们使用哪个并不重要。
无法弄清楚这部分,我很确定一旦看到解决方案我就会想把头撞到墙上...
使用 Linq
扩展函数你可以做到这一点。
Dictionary<char,int> dic1 = ...;
Dictionary<char,int> dic2 = ...;
var result = dic1.Concat(dic2)
.GroupBy(g=>g.Key)
.ToDictionary(x=>x.Key, x=>x.Max(m=>m.Value)) ;
如果您有两个集合,其基础类型包含 key, count
fields/properties
,请尝试使用此方法。
var result = list1.Concat(list2)
.GroupBy(g=>g.Key)
.Select(x=>new // Create an object instead if you have one.
{
x.Key,
x=>x.Max(m=>m.Count)
};
勾选这个Demo
您可以按 Key
和 select 最大 Count
:
分组
var collection1 = "testtt".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() });
var collection2 = "teessst".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() });
var result = collection1.Concat(collection2)
.GroupBy(item => item.Key, item => item.Count)
.Select(g => new { Key = g.Key, Count = g.Max() });
我认为这是相当直接的:
var s1 = new [] { new { Key = 'a', Count = 5 }, new { Key = 'b', Count = 2 } };
var s2 = new [] { new { Key = 'a', Count = 4 }, new { Key = 'c', Count = 7 } };
var result =
s1
.Concat(s2)
.OrderByDescending(x => x.Count)
.GroupBy(x => x.Key)
.SelectMany(x => x.Take(1));
它给了我:
我有 2 个包含字符和字符计数的 IEnumerable 集合(即 s1{Key = 'a' Count='5'} 和 s2{Key='a' Count = '4'})
我想使用 Linq 查询执行以下操作:
如果项目在两个集合中,我只想要集合中计数较高的项目,即 Count=5 from s1
如果该项目仅在一个集合中,则我们使用该项目(不能使用 Distinct,因为它说 IEnumerable Anonymous 不包含 Distinct)
如果项目在两个集合中但它们的数量相等,则我们使用哪个并不重要。
无法弄清楚这部分,我很确定一旦看到解决方案我就会想把头撞到墙上...
使用 Linq
扩展函数你可以做到这一点。
Dictionary<char,int> dic1 = ...;
Dictionary<char,int> dic2 = ...;
var result = dic1.Concat(dic2)
.GroupBy(g=>g.Key)
.ToDictionary(x=>x.Key, x=>x.Max(m=>m.Value)) ;
如果您有两个集合,其基础类型包含 key, count
fields/properties
,请尝试使用此方法。
var result = list1.Concat(list2)
.GroupBy(g=>g.Key)
.Select(x=>new // Create an object instead if you have one.
{
x.Key,
x=>x.Max(m=>m.Count)
};
勾选这个Demo
您可以按 Key
和 select 最大 Count
:
var collection1 = "testtt".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() });
var collection2 = "teessst".GroupBy(c => c).Select(g => new { Key = g.Key, Count = g.Count() });
var result = collection1.Concat(collection2)
.GroupBy(item => item.Key, item => item.Count)
.Select(g => new { Key = g.Key, Count = g.Max() });
我认为这是相当直接的:
var s1 = new [] { new { Key = 'a', Count = 5 }, new { Key = 'b', Count = 2 } };
var s2 = new [] { new { Key = 'a', Count = 4 }, new { Key = 'c', Count = 7 } };
var result =
s1
.Concat(s2)
.OrderByDescending(x => x.Count)
.GroupBy(x => x.Key)
.SelectMany(x => x.Take(1));
它给了我: