List<string> listKeys = new List<string>()
{
"A",
"B",
"C",
"D"
};
List<object> listVals = new List<object>()
{
11,
15,
32,
33
};
将以上两个集合转为Dictionary<string, object> ,即<"A",11>,<"B",15>,<"C",32>,<"D",33>,两个集合通过索引进行关联,即“A”对应索引0,11对应也是索引0,“B”对应索引1,15对应也是索引1,以此类推
我能想到的最简单实现
List<string> listKeys = new List<string>()
{
"A",
"B",
"C",
"D"
};
List<object> listVals = new List<object>()
{
11,
15,
32,
33
};
int i1 = 0, i2 = 0;
var dict =
(from k in listKeys.ToDictionary(_ => i1++)
join v in listVals.ToDictionary(_ => i2++) on k.Key equals v.Key
select new { Key = k.Value, v.Value })
.ToDictionary(k => k.Key, v => v.Value);
foreach (var item in dict)
{
Console.WriteLine(item.Key + ":" + item.Value);
}
public static Dictionary<string, object> Convert(List<string> keys, List<object> values)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
if (keys != null && values != null)
{
int count = keys.Count < values.Count ? keys.Count : values.Count;
for (int i = 0; i < count; i++)
{
if (dict.Keys.Contains(keys[i]))
{
throw new InvalidOperationException("滚");
}
dict.Add(keys[i], values[i]);
}
}
return dict;
}
就这?还是我理解有误?
你的代码直接避免了很多问题、非常棒!
楼上的兄弟写的更严谨一些,我这个没有做任何验证,比较清晰易懂
List<string> listKeys = new List<string>() { "A", "B", "C", "D" };
List<object> listVals = new List<object>() { 11, 15, 32, 33 };
Dictionary<string, object> dict = new Dictionary<string, object>();
for (int i = 0; i < listKeys.Count; i++) {
dict.Add(listKeys[i], listVals[i]);
}