Home > Software design >  Linq get element from string list and a position of a char in this list
Linq get element from string list and a position of a char in this list

Time:11-05

i want to get an element from a list of string and get the position of a char in this list by using linq ?

Exemple :

List<string> lines = new List<string> { "TOTO=1", "TATA=2", "TUTU=3"}
i want to extract the value 1 from TOTO in the list

here is the begin of my code :
var value= lines.ToList().Single(x => x.Contains("TOTO=")).ToString().Trim();
How to continue this code to extract 1 ?

CodePudding user response:

Add this :

value = value[(value.LastIndexOf('=')   1)..];

CodePudding user response:

Using LINQ you can do this:

List<string> lines = new List<string> { "TOTO=1", "TATA=2", "TUTU=3" };

int value = lines
    .Select(line => line.Split('='))
    .Where(parts => parts[0] == "TOTO")
    .Select(parts => int.Parse(parts[1]))
    .Single();

If you always expect each item in that list to be in the proper format then this should work, otherwise you'd need to add some validation.

  • Related