c# - 如何在 C# 中匹配两个列表的项目?

标签 c# .net list

我想根据 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});

A = 1,

B = 4,

C = 2,

D = 3,

E = 5,

最佳答案

目前对您来说最好的选择是Dictionary Class以 list_Position 为键,以 list_Position 为值,这样您就可以根据位置和明智的 Versa 访问值。定义如下:

 Dictionary<int, string> customDictionary= 
            new Dictionary<int, string>();

 customDictionary.Add(1,"A");
 customDictionary.Add(2,"C");
....

如果你想访问值对应的 o 2 意味着你可以使用

string valueAt2 = customDictionary[2]; // will be "C"

如果你想得到key/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; 
}

如果您仍然想使用两个列表意味着您可以考虑这个 Example这意味着,从 list_Position 获取所需元素的位置并获取 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");

关于c# - 如何在 C# 中匹配两个列表的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40012639/

相关文章:

c# - 带 ASP.Net 的命名管道

c# - ExecuteNonQuery 返回 1,即使更新语句没有影响任何行

.net - TFS 中放置文件夹和构建代理工作目录之间的区别

python - 如何同时修改两个相互关联的列表?

python - 为什么 MySQL 连接查询的输出作为嵌套列表项返回?

c# - Windows 服务 : System. Reflection.ReflectionTypeLoadException 被抛出并出现以下错误消息:无法加载一个或多个重新

c# - 在 Python 中加载 DLL 文件和调用函数

python - 如何在不使用加号的情况下在python中合并两个列表

c# - 如何更改 VS2015 中的代码生成策略?

c# - 从 C# 进行 Excel 操作 - 设置 ActiveCell?