[英]C#: Adding data to dictionary
我有一个类似的清单
List<string> TempList = new List<string> { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
我需要将数据从以上列表添加到字典中
Dictionary<int, int> Dict = new Dictionary<int, int>();
所以Dict应该包含
Key --> 66 value --> 67
我需要从第一个字符串([66,X,X])中获取66(第一个值),从第二个字符串([67,X,X])中获取67(第一个值),并将其作为键值对添加到字典中。
现在,我正在按照字符串替换和循环方法进行此操作。
有什么办法可以在LINQ或正则表达式中执行此操作。
在您从列表列表开始发表评论之后,我了解了您的要求。 我在这里重用Jaroslav的“ GetNumber”功能。 用字符串数组array编写了我的示例,但是应该可以正常工作。 如果您有重复的键,则下面的代码将抛出,如果使用字典,我想这就是您想要的。
var input = new []
{
new [] { "[66,X,X]", "[67,X,2]", "[x,x,x]" },
new [] { "[5,X,X]", "[8,X,2]", "[x,x,x]" }
};
var query = from l in input
select new
{
Key = GetNumber(l.ElementAt(0)),
Value = GetNumber(l.ElementAt(1))
};
var dictionary = query.ToDictionary(x => x.Key, x => x.Value);
这是同时使用string.Split()
和Regex的示例:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> data = new List<string>() { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
addToDict(data);
Console.ReadKey();
}
private static void addToDict(List<string> items)
{
string key = items[0].Split('[', ',')[1];
string val = items[1].Split('[', ',')[1];
string pattern = @"(?:^\[)(\d+)";
Match m = Regex.Match(items[0], pattern);
key = m.Groups[1].Value;
m = Regex.Match(items[1], pattern);
val = m.Groups[1].Value;
_dict.Add(key, val);
}
static Dictionary<string, string> _dict = new Dictionary<string, string>();
}
}
我怀疑您的示例非常人为,因此可能会有更好的解决方案,尤其是当您需要将大量字符串处理为键/值对时(我故意对索引值进行硬编码,因为您的示例非常简单并且我不想使答案过于复杂)。 如果输入数据在格式上是一致的,则可以进行假设,例如使用固定索引,但是如果有可能出现差异,则可能需要更多代码来检查其有效性。
您可以使用正则表达式从列表中的每个项目中提取值,如果需要,可以使用LINQ选择两个列表并将它们压缩在一起(在C#4.0中):
var regex = new Regex(@"\d+");
var allValues = TempList.Select(x =>int.Parse(regex.Match(x).Value));
var dictKeys = allValues.Where((x,index)=> index % 2 == 0); //even-numbered
var dictValues = allValues.Where((x,index)=> index % 2 > 0); //odd numbered
var dict = dictKeys.Zip(dictValues, (key,value) => new{key,value})
.ToDictionary(x=>x.key,x=>x.value);
如果使用的是C#3.5,则可以使用Eric Lippert的Zip()实现 。
如果我理解正确:您想创建链接节点,例如66 -> 67, 67 -> 68, ... n -> n+1
吗?
我不会使用LINQ:
private static int GetNumber(string s)
{
int endPos = s.IndexOf(',');
return Int32.Parse(s.Substring(1, endPos-1));
}
并在代码中:
int first, second;
for (int i = 1; i < TempList.Count; i++)
{
first = GetNumber(TempList[i - 1]);
second = GetNumber(TempList[i]);
Dict.Add(first, second);
}
您还应该执行检查等。
该示例假定一个列表至少包含2个项目。
List<List<string>> source = GetSource();
Dictionary<int, int> result = source.ToDictionary(
tempList => GetNumber(tempList[0]),
tempList => GetNumber(tempList[1])
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.