首页 新闻 会员 周边 捐助

C#两个List转为字典

0
悬赏园豆:10 [已解决问题] 解决于 2022-09-07 11:19

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,以此类推

C#
Assur的主页 Assur | 初学一级 | 园豆:6
提问于:2022-09-06 19:16
< >
分享
最佳答案
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);
}
收获园豆:10
dudu | 高人七级 |园豆:30925 | 2022-09-06 20:33
其他回答(2)
1
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;
}

就这?还是我理解有误?

会长 | 园豆:12463 (专家六级) | 2022-09-06 19:46

你的代码直接避免了很多问题、非常棒!

支持(0) 反对(0) IPeanut | 园豆:223 (菜鸟二级) | 2022-09-08 09:32
0

楼上的兄弟写的更严谨一些,我这个没有做任何验证,比较清晰易懂

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]);
}
WmW | 园豆:424 (菜鸟二级) | 2022-09-07 11:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册