List< string>使用LINQ获取以Name =开头的项目 [英] List<string> get item that starts with Name= using LINQ

查看:111
本文介绍了List< string>使用LINQ获取以Name =开头的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从List<string>中检索以Name=开头的项目(值)

How can i retrieve from a List<string> the item(value) that starts with Name=

如果列表包含以下值:

Name=Jhon Smith
Age=20
Location=CityName

我想获取值Jhon Smith.

我确实知道如何使用foreach遍历列表,并且如果以Name=开头的值有一个条件,但是我对LINQ不太满意.

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.

推荐答案

如果集合中没有此类元素,则将引发异常. 您可以使用 FirstOrDefault 并检查是否得到null或元素去检查 是否有比赛.

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)

这不会引发异常:

var prefix = "Name=";
var elem = list.FirstOrDefault(item => item.StartsWith(prefix));
if (elem != null) {
    return elem.Substring(prefix.Length)
} else {
    return null;
}

这篇关于List&lt; string&gt;使用LINQ获取以Name =开头的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆