簡體   English   中英

在列表中查找項目,並使用linq從同一位置的其他列表中獲得其他項目

[英]find item in list , and get other item from other list at same location using linq

我有一堂課,那里有一個列表的集合。 我想在列表之一中搜索參數。 所以我找到列表的位置,我想到達同一班級其他列表的相同位置...

如何實現呢?

void Main()
{
    var myListCollectionObj = new myListCollection();

    Console.WriteLine(myListCollectionObj.firstList);
    Console.WriteLine(myListCollectionObj.secondList);
    Console.WriteLine(myListCollectionObj.thirdList);

    var testFirstList = myListCollectionObj.firstList.Where(x => x == 3); //then i want to get "33", and 333 from secondList and thirdList respectively

    Console.WriteLine(testFirstList);

}

class myListCollection
{
    public List<int> firstList = new List<int>(){ 1, 2, 3, 4, 5};
    public List<string> secondList = new List<string>(){ "11", "22", "33", "44", "55"};
    public List<int> thirdList = new List<int>(){ 111, 222, 333, 444, 555};

}
int index = myListCollectionObj.firstList.IndexOf(3);
string elem2;
int elem3;

if (index >= 0 && index < myListCollectionObj.secondList.Length)
  elem2 = myListCollectionObj.secondList[index]

if (index >= 0 && index < myListCollectionObj.thirdList.Length)
  elem3 = myListCollectionObj.thirdList[index]

您不需要LINQ,僅需要List<T>自己的IndexOf()方法和indexer屬性:

int index = myListCollectionObj.firstList.IndexOf(3);
string secondValue = myListCollectionObj.secondList[index];
int thirdValue = myListCollectionObj.thirdList[index];

您可能想要添加錯誤處理:如果firstList不包含3IndexOf()返回索引-1

我猜如果有多個3值的最好方法是使用簡單的for循環:

var testFirstList = new List<int>();
var testSecondList = new List<string>();
var testThirdList = new List<int>();
for (var i = 0; i < myListCollectionObj.firstList.Length; ++i) {
    if (myListCollectionObj.firstList[i] == 3) {
        testFirstList.Add(myListCollectionObj.firstList[i]);
        testSecondList.Add(myListCollectionObj.secondList[i]);
        testThirdList.Add(myListCollectionObj.thirdList[i]);
    }
}

一個很好的指導原則是,如果您發現自己結合了索引和LINQ,則可能還有其他選擇。 在這種情況下,最好的選擇是使用Zip

這種方法使您可以將3個集合組合在一起並作為單個實體對生成的壓縮集合進行操作,從而不再直接需要索引。

var result = firstList.Zip(
     secondList.Zip(thirdList,
         (b, c) => new { b, c }),
         (a, b) => new { Value1 = a, Value2 = b.b, Value3 = b.c })
     .Where(x => x.Value1 == 3).ToList();

result.ForEach(v => Console.WriteLine(v));

糾正我,如果我錯了,您是在尋找在第一個列表中搜索的商品的索引,然后使用相同的索引從其他列表中檢索

如果是,請嘗試

var testFirstList = myListCollectionObj.firstList.Where(x => x == 3).FirstOrDefault(); //then i want to get "33", and 333 from secondList and thirdList respectively
var index = myListCollectionObj.firstList.IndexOf(testFirstList);

暫無
暫無

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

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