如何将两个LIst结合到字典 [英] How union two LIst to Dictionary
本文介绍了如何将两个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>>();
推荐答案
SAKryukov 对问题的评论是正确的.
要组合两个Lists
,基本上需要一个关系才能知道List2
的哪个item
与List1
的哪个item
相关.在问题中给出了auto - 1q, auto - 2q, auto - 3q
.假设1q, 2q, 3q
分别引用List2的第一,第二,第三项,则可以将它们相应地关联起来.但是,对于List1
中的bus
项,也给出了1q, 2q, 3q
.然后,List2
的相同项目再次与此相关.因此,我认为可以通过将List2
中相应项目的正确index
赋予List1
中项目的方式来关联,如下所示:
The comment by SAKryukov to the question is correct.
To combine twoLists
, basically a relationship is required to know whichitem
ofList2
is to be related to whichitem
ofList1
. In the questionauto - 1q, auto - 2q, auto - 3q
are given. Assuming that1q, 2q, 3q
refer to the first, second, third items of List2 respectively, they can be related accordingly. But then1q, 2q, 3q
are also given forbus
items inList1
. Then again the same items ofList2
are related to these. Hence, I think it can be related by giving properindex
of the corresponding item inList2
to the item inList1
as shown below:
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结合到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文