C# 在逗号分隔的列表中查找字符串值

C# 在逗号分隔的列表中查找字符串值,c#,linq,C#,Linq,我有一个以“标签,位置”形式包含成员的列表(字符串);标签是不同的。我需要一个接受标签参数并返回位置的方法 我可以使用foreach迭代以找到正确的标签,然后使用Split操作列表成员以返回位置。然而,我确信有更好的方法,大概是使用LINQ,沿着 return theList.Single(x => x == theLabel); 但是,这不起作用,因为列表值==标签,位置。请参见下面的代码: string get_location(List<string> list, la

我有一个以“标签,位置”形式包含成员的列表(字符串);标签是不同的。我需要一个接受标签参数并返回位置的方法

我可以使用foreach迭代以找到正确的标签,然后使用Split操作列表成员以返回位置。然而,我确信有更好的方法,大概是使用LINQ,沿着

return theList.Single(x => x == theLabel);
但是,这不起作用,因为列表值==标签,位置。

请参见下面的代码:

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

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

<代码> > P>由于标签是唯一的,您可以考虑将数据转换为<代码>字典< /代码>。您可以将标签保留为,位置保留为

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             
}

正如我和其他两个答案所建议的,这本词典正是为这个目的而设计的。您表达了对迭代dict的关注,而不是认为它可能更难的列表,但事实上它更容易,因为不需要拆分(而且更快)


列表
是字符串列表?为什么不使用字典?是的,列表是字符串列表,例如:label1,location1,然后label2,location2。至于使用字典,我并不反对,但遍历列表已经非常简单了。我希望有一行或两行LINQ选项。@xnguyeng迭代字典同样简单,查找不需要LINQ,字典当然是你应该做的。从他的其他问题来看,它的管理数据,因此,他应该立即将其存储为dict并放弃列表和转换。我完全同意@Wobbles.You's correct@Wobbles,这些值存储在格式良好且结构化的csv文件中。我已经有了将csv读入列表的方法,所以我从那里开始。也许我应该问一个新的/更好的问题:如何将csv直接读入字典:)。@xnguyeng请看下面,如果它是csv,我建议放弃我们所说的一切,使用某种类型的
可枚举的
。此外,如果csv是仅来自应用程序并由应用程序使用的数据,还有更好更简单的序列化格式,我最近开始偏爱JSON。这看起来很完美,谢谢。最后[标签]的功能是什么?不是在第一个lambda表达式中分配了键和值吗?[label]在字典中查找与key==label对应的值。啊,当然,谢谢。虽然其他人建议完全跳过列表(因为源代码是csv)并直接进入字典,但你是第一个对我描述不完整的问题给出正确答案的人。谢谢@Wobbles,我会看看是否可以按照你描述的思路实现。
var location = string.Empty;
if(lableLocatonDict.TryGetValue("LabelToCheck",out location))
{
   // location will have the value here             
}
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);
}
public class LocationInfo
{
    String Label {get;set;}
    String Location {get;set;}
    String Description {get;set;}
}

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