Reputation: 6029
How can i retrieve from a List<string>
the item(value) that starts with Name=
If the list contains the values:
Name=Jhon Smith
Age=20
Location=CityName
I want to get the value Jhon Smith
.
I do know how to traditionally loop through the list using foreach and have a condition if value starts with Name=
... but I'm not that good with LINQ.
Upvotes: 0
Views: 11930
Reputation: 10350
A slightly modernized and updated version that:
"Name=".Length
):var list = new List<string> { "Name=Jhon Smith", "Age=20", "Location=CityName" };
const string namePrefix = "Name=";
string? name = list.FirstOrDefault(s => s.StartsWith(namePrefix));
name = name?[namePrefix.Length..]; // Jhon Smith
Upvotes: 0
Reputation: 35891
Use Single
or SingleOrDefault
like this:
var result = list.Single(s => s.StartsWith("Name=")).Substring(5);
or
string result = string.Empty;
var element = list.SingleOrDefault(s => s.StartsWith("Name="));
if (element == null)
{
//"Name=" not present, throw an exception
}
result = element.Substring(5);
or similarly with First
, or FirstOrDefault
depending on what you exactly want.
There was another interesting answer by the user canon, but was deleted (I don't know why):
var result = list
.Where(x => x.StartsWith("Name="))
.Select(x => x.Substring(5))
.FirstOrDefault();
Its advantage is that it won't throw regardless of the input data.
Upvotes: 3
Reputation: 10588
This will throw an exception if there is no such element in the collection.
You can use FirstOrDefault
and check if you get null or an element to check
whether there was a match or not.
list.First(x => x.StartsWith("Name=")).Substring(5)
This won't throw an exception:
var prefix = "Name=";
var elem = list.FirstOrDefault(item => item.StartsWith(prefix));
if (elem != null) {
return elem.Substring(prefix.Length)
} else {
return null;
}
Upvotes: 6
Reputation: 155065
String match = list.FirstOrDefault( str => str.IndexOf("Name=", StringComparison.InvariantCulture) > -1 );
return match.Substring("Name=".Length);
Upvotes: 1