簡體   English   中英

如何在C#中匹配兩個列表的項?

[英]How to match items of two list in C#?

我想獲取基於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

目前,最適合您的選擇是字典類 ,將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"

如果要獲取對應於特定值的密鑰,則可以使用如下所示:

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_Position並在list_Position獲取該元素,請記住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");

您可以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

像這樣:

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

//listId==4

無需使用兩個單獨的列表,一個用於值,一個用於位置,而是選擇字典,這將使您的生活更加輕松,因為它可以封裝一個值和一個鍵。

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

您可以使用Dictionary<int, string>代替List<int>List<string>如下所示:

Dictionary<int, string> yourDic = new Dictionary<int, string>();
yourDic.Add(1, "A");
// ... and so on

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM