![](/img/trans.png)
[英]Use C# to check is string contains an integer in a given range of numbers
[英]Check if a CSV string contains a given value C#
我正在讀取以逗號分隔的數字ID列表,該列表以字符串形式存儲。 我需要檢查該列表中是否已存在ID。 例如:
“ 1,2,3”
如果我檢查“ 2”,我應該找到它,但是如果我檢查“ 22”,我就找不到。
什么是最簡單直接的方法?
我當前的代碼如下:
HttpCookie cookie = Request.Cookies.Get("wishlist");
if (cookie != null)
{
var JSONstring = cookie.Value; //Cookie stored as JSON
Dictionary<string, List<dynamic>> jObj = JsonConvert.DeserializeObject<Dictionary<string, List<dynamic>>>(JSONstring);
// Retreive only the nodeId of each item and store it in a CSV list
string umbracoCSV = String.Join(",", jObj.SelectMany(x => x.Value).Select(x => x.nodeId));
// Convert the CSV into an IEnumerable list of ints
IEnumerable<int> umbracoNodeIdList = umbracoCSV.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
foreach(int umbracoNodeId in umbracoNodeIdList){
if(umbracoNodeId == 2){
// Do code if it matches
}else{
// Do code if it doesn't match
}
}
}
如您所見,此代碼包括一個不必要的循環,實際上我希望能夠直接解析CSV字符串以獲得該值,而不是執行嵌套循環(因為如果不可能,此循環將嵌套在另一個循環中)。
任何幫助將不勝感激。
您可以使用Any
方法簡化代碼:
bool isExists = umbracoCSV.Split(',').Any(x => x == "2");
if(isExists) { }
您可以在此處選擇以下幾種方式:
在字符串中找到2
if(umbracoCSV.Contains(",2,") //,2, is to rule out 22 //Do something
使用正則表達式而不是String.Contains
分割字符串並在其上使用Any
var toArray = umbracoCSV.Split(','); if(toArray.Any(x => x == "2") //Do something
如果您仍然將其IEnumerable<int>
,則也可以使用Any
if(umbracoNodeIdList.Any(x => x == 2) //Do something
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.