如何通过分隔符和多个组拆分字符串并在Linq中计算它们?

时间:2018-02-06 07:56:43

标签: c# linq

我有一个LogData列表,其设计如下。

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let names = tempArray.flatMap({ $0["Name"] })
print(names) // ["ABC", "qwe", "rty", "uio"]

我希望得到如下结果。

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));

我想分组并且不仅要计算分割字符串(indexpattern),还要计算 类型也是。我想通过OrderByDescending(Count)计算并显示它们。

我认为有多个小组。 我应该如何使用Linq?

3 个答案:

答案 0 :(得分:4)

您可以使用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()
          };

(可根据需要在最终order by之前添加Select子句。)

答案 1 :(得分:3)

你可能会陷入SelectMany;所有其他命令都非常明显:

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));

答案 2 :(得分:0)

这是改进版本或以前的答案。

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
}