[英]How to compare string with specific part of array item?
I have an array arr[] of string type with array-items as follows:我有一个带有数组项的字符串类型数组 arr[] ,如下所示:
arr[0]= "2/13/2019|202"
arr[1]= "2/14/2019|197"
arr[2]= "2/15/2019|101"
arr[4]= "2/16/2019|271"
arr[5]= "2/17/2019|199"
I want to get an array-item that matches my string "2/15/2019" so I can get "2/15/2019|101".我想得到一个与我的字符串“2/15/2019”相匹配的数组项,这样我就可以得到“2/15/2019|101”。 in short, I just want to compare my string with the array-item string till "|"
简而言之,我只想将我的字符串与数组项字符串进行比较,直到“|” and rest strong will not be considered for comparison.
和休息强将不考虑比较。 how can I get it?
我怎么才能得到它?
You can use Linq to get the data you are looking for.您可以使用 Linq 来获取您要查找的数据。
?.
?.
after FirstOrDefault()
method to ensure you dont get NullReferenceException when you run Split()
.FirstOrDefault()
方法之后,以确保您在运行Split()
时不会得到 NullReferenceException 。var result = arr.FirstOrDefault(x => x.Contains("2/15/2019"))?.Split('|')[1];
// result contains 101
Enumerable.FirstOrDefault : Returns the first element of a sequence, or a default value if no element is found Enumerable.FirstOrDefault :返回序列的第一个元素,如果没有找到元素,则返回默认值
You could use Where
and StartWith
你可以使用
Where
和StartWith
var results = arr.Where(x => x.StartsWith("2/15/2019"));
Additional Resources其他资源
Enumerable.Where Method Enumerable.Where 方法
Filters a sequence of values based on a predicate.
根据谓词过滤一系列值。
String.StartsWith Method String.StartsWith 方法
Determines whether the beginning of this string instance matches a specified string.
确定此字符串实例的开头是否与指定的字符串匹配。
Use where and contains使用 where 和 contains
string getdata = "2/15/2019";
string[] arr = new string[5];
arr[0] = "2/13/2019|202";
arr[1] = "2/14/2019|197";
arr[2] = "2/15/2019|101";
arr[3] = "2/16/2019|271";
arr[4] = "2/17/2019|199";
var op = arr.Where(a => a.Contains(getdata)).FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.