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

7
根据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.
这是一组关于数字的简单赋值语句,每个字母代表一个数字。

1
你可以使用键值对列表。 - Awais Mahmood
6
在提出这样的问题之前,为什么不先尝试一下去实现目标呢? - Lyubomyr Shaydariv
5个回答

13

此刻最适合您的选择是使用Dictionary Class,以list_Position作为键和list_Position作为值,这样您就可以根据位置访问值。定义将如下所示:

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

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

如果您想访问与 2 相对应的值,可以使用

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

如果你想获取与特定值对应的键/键,可以使用以下方法:

var resultItem = customDictionary.FirstOrDefault(x=>x.value=="C");
if(resultItem !=null) // FirstOrDefault will returns default value if no match found
{
   int resultID = resultItem.Key; 
}

如果您仍然想使用两个列表,那么可以考虑这个示例,也就是从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");

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();

上面的代码返回 id = 4


3

像这样:

var letterIndex = list_Position.indexOf(B);
var listId = (letterIndex + 1 > list_Id.Count) ? -1 : list_Id[letterIndex];

//listId==4

3

不要使用两个单独的列表来存储值和位置,而是选择使用字典,这将使您的生活更轻松,因为它可以封装一个值和一个键。

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

dictionary.Add(1, "A");
dictionary.Add(2, "B");
dictionary.Add(3, "C");
dictionary.Add(4, "D");
dictionary.Add(5, "E");

您可以在字典上执行的一些操作包括:

检查一个键是否存在于字典中:

if (dictionary.ContainsKey(1))

检查字典中是否存在某个值:

if (dictionary.ContainsValue("E"))

访问具有特定键的值:

string value = dictionary[1];

使用foreach循环遍历一对:

foreach (KeyValuePair<string, int> pair in dictionary )
{
    Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}

使用 var 关键字枚举字典

foreach (var pair in dictionary)
{
    Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}

将密钥存储在列表中,并通过列表循环。

List<string> list = new List<string>(dictionary.Keys);
foreach (string something in list)
{
    Console.WriteLine("{0}, {1}", something, dictionary[something]);
}

从字典中移除值

dictionary.Remove("A");

2
您可以使用 Dictionary<int, string> 代替像这样的 List<int>List<string>:
Dictionary<int, string> yourDic = new Dictionary<int, string>();
yourDic.Add(1, "A");
// ... and so on

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接