在使用anonymouse对象进行分组时,如何忽略linq groupby中的case [英] How do I ignore case in linq groupby when grouping using an anonymouse object
问题描述
我有一个查询,我希望在GroupBy基于TeamID和ActivityName的地方运行。 TeamID是一个int,ActivityName是一个字符串。我想执行GroupBy查询,其中GroupBy中的键是(TeamID,ActivityName),在ActivityName中忽略该大小写。下面的代码返回4组,因为活动根据内容或案例都是不同的,我希望通过忽略大小写为2。我已经尝试将StringComparer.InvariantCultureIgnoreCase添加到查询中但是我得到一个编译错误,指出方法的类型参数'System.Linq.Enumerable.GroupBy< tsource,tkey,tresult>(System.Collections.Generic.IEnumerable< tsource>, System.Func< tsource,tkey>,System.Func< tkey,system.collections.generic.ienumerable>< tsource>,TResult>'无法从用法中推断出来。请尝试明确指定类型参数。我也尝试过在查询中使用ToUpper()但没有成功。
我无法弄清楚应该怎么做,任何帮助都将不胜感激。
我尝试过:
I have a query that I want to run where I GroupBy based on TeamID and ActivityName. The TeamID is an int and the ActivityName is a string. I want to perform a GroupBy query where the key in the GroupBy is (TeamID, ActivityName) with the case being ignored in the ActivityName. The code below returns 4 groups as the the activities are all different based on content or case, I want there to be 2 by ignoring the case. I have tried adding StringComparer.InvariantCultureIgnoreCase to the query but I get a compilation error stating "The type arguments for method 'System.Linq.Enumerable.GroupBy<tsource,tkey,tresult>(System.Collections.Generic.IEnumerable<tsource>, System.Func<tsource,tkey>, System.Func<tkey,system.collections.generic.ienumerable><tsource>,TResult>' cannot be inferred from the usage. Try specifying the type arguments explicitly." I have also tried using ToUpper() in the query but with no success.
I can't figure out how this should be done, any help would be appreciated.
What I have tried:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
PerformQuery();
}
public void PerformQuery()
{
List<team> teams = new List<team>();
teams.Add(new Team { TeamId = 1, ActivityName = "Football" });
teams.Add(new Team { TeamId = 1, ActivityName = "football" });
teams.Add(new Team { TeamId = 2, ActivityName = "Rugby" });
teams.Add(new Team { TeamId = 2, ActivityName = "rugby" });
var activities = teams
.GroupBy(e => new { e.TeamId, e.ActivityName });
}
}
public class Team
{
public int TeamId { get; set; }
public string ActivityName { get; set; }
}
推荐答案
尝试:
Try:
var activities = teams.GroupBy(e => new { e.TeamId, e.ActivityName.ToLower() });
:doh: - 我需要更多的咖啡...
试试这个:
:doh: - I need more coffee...
Try this:
public class Team
{
public int TeamId { get; set; }
public string ActivityName { get; set; }
public string ActivityNameLower { get { return ActivityName.ToLower(); } }
}
然后:
And then:
var activities = teams.GroupBy(e => new { e.TeamId, e.ActivityNameLower });
检查这个
check this
var activities = teams.GroupBy(e => new { TeamId = e.TeamId, ActivityName = e.ActivityName.ToLower() }).ToList();
foreach (var item in activities)
{
var key = item.Key;
var items = item.ToList();
}
这篇关于在使用anonymouse对象进行分组时,如何忽略linq groupby中的case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!