0

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.

4

3 回答 3

6

如果集合中没有这样的元素,这将引发异常。您可以使用FirstOrDefault并检查是否获得 null 或元素来检查是否存在匹配项。

list.First(x => x.StartsWith("Name=")).Substring(5)

这不会抛出异常:

var prefix = "Name=";
var elem = list.FirstOrDefault(item => item.StartsWith(prefix));
if (elem != null) {
    return elem.Substring(prefix.Length)
} else {
    return null;
}
于 2013-10-02T20:32:13.107 回答
3

使用SingleSingleOrDefault像这样:

var result = list.Single(s => s.StartsWith("Name=")).Substring(5);

或者

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);

或类似First, 或FirstOrDefault取决于你到底想要什么。

用户canon有另一个有趣的答案,但被删除(我不知道为什么):

var result = list
              .Where(x => x.StartsWith("Name="))
              .Select(x => x.Substring(5))
              .FirstOrDefault();

它的优点是无论输入数据如何都不会抛出。

于 2013-10-02T20:32:30.707 回答
1
String match = list.FirstOrDefault( str => str.IndexOf("Name=", StringComparison.InvariantCulture) > -1 );
return match.Substring("Name=".Length);
于 2013-10-02T20:32:13.063 回答