[英]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.