Extract part of a string

I have a collection. The column has rows:

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

etc. I need to extract only the Name bit from the string. For example, here I have to extract the text "regal"

I am struggling with the request:

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

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

[Edit]: What if I need to add a GroupBy clause

Collection.GroupBy (????);

+1
source share
5 answers

Another LINQ-style answer (no dictionary overhead):

var name = (from part in location.Split(',')
            let pair = part.Split('=')
            where pair[0].Trim() == "Name"
            select pair[1].Trim()).FirstOrDefault();

re group (change):

    var records = new[] {
        new {Foo = 123, Location="Theater=2, Name=regal, Area=Area1"},
        new {Foo = 123, Location="Name=cineplex, Area=Area1, Theater=1"},
        new {Foo = 123, Location="Theater=2, Area=Area2, Name=regal"},
    };
    var qry = from record in records
              let name = (from part in record.Location.Split(',')
                          let pair = part.Split('=')
                          where pair[0].Trim() == "Name"
                          select pair[1].Trim()).FirstOrDefault()
              group record by name;
    foreach (var grp in qry)
    {
        Console.WriteLine("{0}: {1}", grp.Key, grp.Count());
    }
+1
source

Extension of Paul's answer:

var location = "Theater=2, Name=regal, Area=Area1";

var foo = location
    .Split(',')
    .Select(x => x.Split('='))
    .ToDictionary(x => x[0].Trim(), x => x[1]);

Console.WriteLine(foo["Name"]);

This fills the source line in the dictionary for convenience. Again, error checking or something else.

+3
source
Location.Split(",").Select(x => x.Split("=")[1])

, - : 1)

+2

- IndexOf/Substring:

string location = "Theater=2, Name=regal, Area=Area1";

int startPos = location.IndexOf("Name=") + 5;
int endPos = location.IndexOf(",", startPos);

string name = location.Substring(startPos, endPos - startPos);
+2

If Regex is an option, you can use the lookaround construct to even out the exact match. The sample I used below should work fine in C #. The best part is that it will continue to work even if additional comma-separated elements are added to the part of the name.

    System.Text.RegularExpressions.Match m =
        System.Text.RegularExpressions.Regex.Match(
            "Theater=2, Name=regal, Area=Area", @"(?<=Name=)[a-zA-Z0-9_ ]+(?=,)");
    Console.WriteLine(m.Value);
+2
source

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


All Articles