簡體   English   中英

在逗號分隔列表中查找字符串值

[英]Find string value in comma-separated list

我有一個列表(字符串),其成員的形式為'label,location'; 標簽是不同的。 我需要一個接受label參數並返回位置的方法。

我可以使用foreach迭代查找正確的標簽,然后使用Split操作列表成員以返回位置。 但是我確信有更好的方法,大概是使用LINQ,沿着這個方向

return theList.Single(x => x == theLabel);

但這不起作用,因為列表值== label,location。

請參閱以下代碼:

string get_location(List<string> list, label)
{
  return list.Select(s => s.Split(',')).ToDictionary(s => s[0], s => s[1])[label];
}

如果同一列表中有多個請求,則最好保存該字典,然后重新使用查詢的所有標簽:

var map = list.Select(s => s.Split(',')).ToDictionary(s => s[0], s => s[1]);

或者:

var map = new Dictionary<string, string>();
list.ForEach(s => { var split = s.Split(','); map.Add(split[0], split[1]); });

由於標簽是唯一的,您可以考慮將數據轉換為dictionary<string,string> 您可以將標簽作為和位置作為

var lableLocatonDict = theList.Select(item => item.Split(','))
                                      .ToDictionary(arr => arr[0], arr => arr[1]);

現在,要訪問特定標簽(鍵)的位置(值),您只需執行此操作即可

var location = lableLocatonDict["LabelToCheck"];

如果要在訪問之前檢查字典中是否存在項,則可以使用ContainsKey方法。

if(lableLocatonDict.ContainsKey("LabelToCheck"))
{
    var location = lableLocatonDict["LabelToCheck"];
}

或者TryGetValue

var location = string.Empty;
if(lableLocatonDict.TryGetValue("LabelToCheck",out location))
{
   // location will have the value here             
}

正如我和其他2個答案所推薦的那樣,Dictionary就是為了這個目的而設計的。 你表示擔心迭代dict而不是列表認為它可能更難,但事實上它更容易,因為不需要分裂(並且更快)。

Dictionary<String,String> locations = new Dictionary<String,String>();

//How to add locations
locations.Add("Sample Label","Sample Location");

//How to modify a location
locations["Sample Label"] = "Edited Sample Locations";

//Iterate locations
foreach (var location in locations)
{
    Console.WriteLine(location.key);
    Console.WriteLine(location.value);
}

我甚至會進一步說明你的應用程序的未來證明並添加能夠存儲在每個位置的更多信息,你應該真正使用ObservableCollection<T>其中T是一個自定義類對象:

public class LocationInfo
{
    String Label {get;set;}
    String Location {get;set;}
    String Description {get;set;}
}

ObservableCollection<LocationInfo> Locations = new ObservableCollection<LocationInfo>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM