在数组列表中查找变量

本文关键字:查找 变量 列表 数组 | 更新日期: 2023-09-27 18:34:04

假设我有一个数组列表,其中包含如下:

var listArray = new List<string[]>():

第一个数组 = {代码, ID_1, PK_1, ID_2, PK_2}//不知何故像一个标题

第二个数组 = {85734, 32343, 1, 66544, 2}

第三个数组 = {59382, 23324, 1, 56998, 2}

第 4 个数组 = {43234, 45334, 1, 54568, 2}

这些数组将被添加到"listArray"中。

listArray.Add(array);

我应该怎么做才能匹配列表中的变量?

例如:如果数组的ID_1是'32343',ID_2 = '66544'。

在数组列表中查找变量

// create
var listArray = new List<string[]>():
string whatIWantToFind = "1234";
string[] mySearchArray = new string[] {"1234", "234234", "324234"};
// fill your array here...
// search
foreach(string[] listItem in listArray)
{
    // if you want to check a single item inside...
    foreach(string item in listItem)
    {
         // you can compare
         if(item == whatIWantToFind)
         {
         }
         // or check if it contains
         if(item.Contains(whatIWantToFind))
         {
         }
    }
    // to compare everything..
    bool checked = true;
    for(int i = 0; i < listItem.lenght; i++)
    {
       if(!listItem[i].Equals(mySearchArray[i])
       {
           checked = false; break;
       }
    }
    // aha! this is the one
    if(checked) {}
}

如果创建一个包含一个数组的所有数据的类,则可以创建这些对象的主数组。例如:

public class ListItem {
    public string code, ID_1, PK_1, ID_2, PK_2;
}

然后你可以使用这个类:

var listArray = new List<ListItem>();
listArray.add(new ListItem(){ code = 85734, ID_1 = 32343, PK_1 = 1, ID_2 = 66544, PK_2 = 2});
listArray.add(......);

然后,要查找数据,您可以在数组中的对象上使用字段访问器:

foreach(var item in listArray)
{
    if (item.ID_1.equals("32343") && item.ID_2.equals("66544"))
        Console.WriteLine("Found item.");
}
var listArray = new List<string[]>
            {
                new []{ "code", "ID_1", "PK_1", "ID_2", "PK_2"}, 
                new []{ "85734", "32343", "1", "66544", "2"},
                new []{"59382", "23324", "1", "56998", "2"}
            };
 var index = listArray.First().ToList().IndexOf("ID_1");
 var result = listArray.Where((a, i) => i > 0 && a[index] == "32343").ToList();