Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select each splited string and group by with another members in linq?

Tags:

How to select many split string and group by with another members in linq?

class LogData
{
  public string IndexPattern {get; set;}
  public string Version {get;set;}
  public string Type1 {get; set;}
  public string Type2 {get; set;}

  //here has a constructor of this class
}

I have a list of Log Data Which have a many log datum. The index pattern is the set of log index which use the delimiter ",".

List<LogData> logList = new List<LogData>();
logList.add(new LogData("1,2,4", "Ver1", "pro" , "etc" ) );
logList.add(new LogData("1", "Ver2", "pro" , "etc" ) );
logList.add(new LogData("2", "Ver1", "pro" , "etc" ) );
logList.add(new LogData("1,2,4", "Ver1", "pro" , "etc" ) );
logList.add(new LogData("1,5", "Ver2", "pro" , "set" ) );

And i want split index patterns and group by all member like this.

[Index] [Version] [Type1] [Type2] [Count]
  1        Ver1     pro      etc    2
  2        Ver1     pro      etc    2
  4        Ver2     pro      etc    2
  1        Ver2     pro      etc    1
  1        Ver2     pro      set    1
  5        Ver2     pro      set    1
  4        Ver2     pro      set    1

And i write linq like this to group by first..

var LogGroup = HackingLogs.GroupBy(g => new {
              IndexPattern = g.IndexPattern.SelectMany( new { Index = c => c 
               }),  //I must select many to get each splited  string
                g.Version,
                g.Type1,
                g.Type2
 }); //I group by this for each splited string and all member pairs to select 

But it can not group by. so i can not use select. May i have some answer for this problem?

like image 707
summation Avatar asked Feb 09 '18 06:02

summation


1 Answers

You can first flatten the IndexPattern using SelectMany and project all other elements. Finally group by all columns and get the Count. This should give you the expected output:-

 var res = logList.SelectMany(x => x.IndexPattern.Split(',')
                                  .Select(z => new 
                                      { 
                                           Index = z, 
                                           Version = x.Version, 
                                           Type1 = x.Type1, 
                                           Type2 = x.Type2 
                                      }))
                   .GroupBy(x => new { x.Index, x.Version, x.Type1, x.Type2 })
                   .Select(x => new
                        {
                            Index = x.Key.Index,
                            Version = x.Key.Version,
                            Type1 = x.Key.Type1,
                            Type2 = x.Key.Type2,
                            Count = x.Count()
                        });

Working Fiddle.

like image 134
Rahul Singh Avatar answered Sep 19 '22 13:09

Rahul Singh