GroupBy row and graph in LINQ

I have a collection. The column has rows:

Location="Theater=1, Name=regal, Area=Area1"

Location="Theater=34, Name=Karm, Area=Area4445"

etc. I need to extract only the Name bit from the string. For example, here I have to extract the text "regal" and group the query. Then display the result as

Name=regal Count 33
Name=Karm  Count 22

I am struggling with the request:

Collection.Location.GroupBy (????); (what to add here)

What is the shortest and most accurate way to do this?

+3
source share
3 answers

Another Linq + Regex approach:

string[] Location = {
                        "Theater=2, Name=regal, Area=Area1",
                        "Theater=2, Name=regal, Area=Area1",
                        "Theater=34, Name=Karm, Area=Area4445"
                    };

var test = Location.Select(
                            x => Regex.Match(x, "^.*Name=(.*),.*$")
                                      .Groups[1].Value)
                   .GroupBy(x => x)
                   .Select(x=> new {Name = x.Key, Count = x.Count()});

Query result for test strings

linq-regex.jpg

+10
source

Once you have extracted the string, just group it and count the results:

var query = from location in locations
            let name = ExtractNameFromLocation(location)
            group 1 by name in grouped
            select new { Name=grouped.Key, Count=grouped.Count() };

. , - . VJ LINQ to Objects, Push LINQ, LINQ.

EDIT: ExtractNameFromLocation , ,

public static string ExtractNameFromLocation(string location)
{
    var name = (from part in location.Split(',')
                let pair = part.Split('=')
                where pair[0].Trim() == "Name"
                select pair[1].Trim()).FirstOrDefault();
    return name;
}
+1

Here is another alternative LINQ solution with a working example.

static void Main(string[] args)
{
    System.Collections.Generic.List<string> l = new List<string>();
    l.Add("Theater=1, Name=regal, Area=Area"); l.Add("Theater=34, Name=Karm, Area=Area4445");

    foreach (IGrouping<string, string> g in l.GroupBy(r => extractName(r)))
    {
        Console.WriteLine( string.Format("Name= {0} Count {1}", g.Key, g.Count())  );
    }
}
private static string extractName(string dirty)
{
    System.Text.RegularExpressions.Match m =
        System.Text.RegularExpressions.Regex.Match(
        dirty, @"(?<=Name=)[a-zA-Z0-9_ ]+(?=,)");

    return m.Success ? m.Value : "";
}
+1
source

Source: https://habr.com/ru/post/1703077/


All Articles