我想基于List_Position得到list_ID值.我应该怎么做?谢谢
List<int> list_ID = new List<int> (new int[ ] { 1, 2, 3, 4, 5 });
List<string> list_Position = new List<string> (new string[ ] { A, C, D, B, E});
Run Code Online (Sandbox Code Playgroud)
A = 1,
B = 4,
C = 2,
D = 3,
E = 5,
suj*_*lil 13
此时最佳选择是Dictionary Class,其中list_Position为键,list_Position为value,因此您可以根据位置访问值,反之亦然.定义如下:
Dictionary<int, string> customDictionary=
new Dictionary<int, string>();
customDictionary.Add(1,"A");
customDictionary.Add(2,"C");
....
Run Code Online (Sandbox Code Playgroud)
如果要访问值对应o 2
表示可以使用
string valueAt2 = customDictionary[2]; // will be "C"
Run Code Online (Sandbox Code Playgroud)
如果要获得与特定值对应的键/ s意味着您可以使用如下所示:
var resultItem = customDictionary.FirstOrDefault(x=>x.value=="C");
if(resultItem !=null) // FirstOrDefault will returns default value if no match found
{
int resultID = resultItem.Key;
}
Run Code Online (Sandbox Code Playgroud)
如果你仍然想要使用两个列表意味着你可以考虑这个例子这意味着,从list_Position
list 获取所需元素的位置并获取list_ID列表中此位置的元素,请记住list_ID的数量必须大于或等于元素与list_Position中的元素相同.代码将是这样的:
string searchKey="D";
int reqPosition=list_Position.IndexOf(searchKey);
if(reqPosition!=-1)
{
Console.WriteLine("Corresponding Id is {0}",list_ID[reqPosition]);
}
else
Console.WriteLine("Not Found");
Run Code Online (Sandbox Code Playgroud)
Gio*_*sos 10
您可以使用zip
这两个列表,然后对压缩列表执行linq查询:
int? id = list_Position.Zip(list_ID, (x, y) => new { pos = x, id = y })
.Where(x => x.pos == "B")
.Select(x => x.id)
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
上面的代码返回id = 4
.
像这样:
var letterIndex = list_Position.indexOf(B);
var listId = (letterIndex + 1 > list_Id.Count) ? -1 : list_Id[letterIndex];
//listId==4
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1210 次 |
最近记录: |