C# 如何按delimeter和multiple group by拆分字符串并在Linq中计数?
我有一个日志数据列表,其设计如下C# 如何按delimeter和multiple group by拆分字符串并在Linq中计数?,c#,linq,C#,Linq,我有一个日志数据列表,其设计如下 public class LogDataEntity { public string IndexPattern; public int Type; public LogDataEntity(string pattern , int type) { IndexPattern = pattern; Type = type; } } List<LogDataEntity> list =
public class LogDataEntity
{
public string IndexPattern;
public int Type;
public LogDataEntity(string pattern , int type)
{
IndexPattern = pattern;
Type = type;
}
}
List<LogDataEntity> list = new List<LogDataEntity>();
list.add(new LogDataEntity("1,2,9,10", 2));
list.add(new LogDataEntity("1,10", 1));
list.add(new LogDataEntity("1,2,3", 2));
list.add(new LogDataEntity("3,9,10", 3));
list.add(new LogDataEntity("9,10", 2));
list.add(new LogDataEntity("9,10", 2));
[Index] [Type] [Count]
10 : 2 3
9 : 2 3
1 : 2 2
3 : 1 2
2 : 2 2
3 : 3 1
9 : 3 1
10 : 3 1
1 : 1 1
我想分组,不仅计算分割的字符串(indexpattern),还计算
我也要打字。我想通过OrderByDescending(计数)来计数和显示它们
我认为有多个分组。
如何使用Linq执行此操作?您可以使用
SelectMany
创建(索引、类型)对列表,然后分组并计数以执行其余操作:
var pairs = data.SelectMany(x => x.IndexPattern
.Split(",")
.Select(y => new {Index = y, Type = x.Type});
var res = from p in pairs
group p by new { p.Index, p.Type } into grp
select new {
Index = grp.Key.Index,
grp.Key.Type,
grp.Count()
};
(可以根据需要在最终的
选择之前添加按
排序的子句)。您可能陷入了选择多个;所有其他命令都非常明显:
var result = list
.SelectMany(record => record
.IndexPattern
.Split(',')
.Select(item => {
index = item,
type = record.Type,
}))
.GroupBy(item => item)
.OrderByDescending(chunk => chunk.Count())
.Select(chunk => $"{chunk.index,-10} : {chunk.type,-10} {chunk.Count()}");
Console.WriteLine(string.Join(Environment.NewLine, result));
这是改进版或以前的答案
var pairs = Logs.SelectMany(x => x.IndexPattern.Split(',').Select(y => new {
Index = y, Type= x.Type }));
var pairs2 = (from p in pairs group p by p into grp select new { Index =
grp.Key.Index, Reason = grp.Key.Type, Count = grp.Count() }
).OrderByDescending(p => p.Count);
foreach (var i in pairs2)
{
//print with i
}
实际上,你的问题几乎是完美的,你有一个复制粘贴的例子,用最少的程序来重现问题,样本输入和预期输出。我想唯一没有得到几张赞成票的就是你自己的一次尝试。在那里你表明你至少已经尝试了任何方法来解决它。我会投赞成票;)哦很抱歉,我得到了下面两个人的提示,我已经自我回答了这个问题的完整linq代码。这只是一个如何提高问题质量的建议。“我已经自我回答了我完整的linq代码”对你有好处。但是这不会影响你问题的质量。谢谢你的回答,但是我不能在这里使用grp.count()。可能这不是一个函数。@summation当然是一个函数,但如果没有确切的错误消息,很难判断问题是什么。感谢@Richard和Dmitry Bychenko的回答。我终于在这两个答案中得到了一个提示。下面是我的linq code.var pairs=Logs.SelectMany(x=>x.IndexPattern.Split(',')。Select(y=>new{Index=y,Type=x.Type});var pairs2=(从成对的p组p逐p进入grp,选择新的{Index=grp.Key.Index,Reason=grp.Key.Type,Count=grp.Count()});谢谢你的回答~!