本文介绍了如何将两个LIst结合到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表Lst1< string>和Lst2< string>
I have two lists Lst1<string> and Lst2<string>
Lst1 Lst2
auto - 1q n122
auto - 2q n341
auto - 3q n461
bus- 1q n132
bus- 2q n441
bus- 3q n761
我想成为:
I want that''s become :
auto
n122
n341
n461
bus
n132
n441
n761
如何使用
How make it with
Dictionary<string, List<string>> axxx = new Dictionary<string, List<string>>();
推荐答案
void Main()
{
List<string> list1 = new List<string>(){"auto - 1","auto - 2","auto - 3","bus - 4","bus - 5","bus - 6"};
List<string> list2 = new List<string>(){"n122","n341","n461","n132","n441","n761"};
Dictionary<string, List<string>> refDic = new Dictionary<string, List<string>>();
foreach(string item in list1){
string[] keyInd=item.Split(new char[]{'-'});
int ind = int.Parse(keyInd[1].Trim())-1;
string refValue = ind < list2.Count ?
list2[ind] : string.Empty;
List<string> refValues;
if (!refDic.TryGetValue(keyInd[0].Trim(),out refValues)){
refValues = new List<string>();
refDic.Add(keyInd[0].Trim(),refValues);}
refValues.Add(refValue);
}
}
//The contents of refDic will look like
//Key - auto
//Value - List<string> of
//n122
//n341
//n461
//
//Key - bus
//Value - List<string> of
//n132
//n441
//n761
这篇关于如何将两个LIst结合到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!