我有兩個list<int>
類型的列表,我知道我們可以找到兩個列表之間的公共元素。但是有沒有什麼辦法可以在相交列表中獲取常用元素和相應的常用元素索引,或者我需要遍歷每個元素找到索引。從兩個列表中獲取具有索引的常用元素C#
回答
LINQ有使用索引投影序列的操作,但是這並沒有內置到查詢表達式語法中,因此您必須使用「常規」擴展方法調用來啓動。之後,它是相當容易的,雖然可能只是簡單不使用LINQ,說實話:
var pairs1 = list1.Select((value, index) => new { value, index });
var pairs2 = list2.Select((value, index) => new { value, index });
var matches = from pair1 in pairs1
join pair2 in pairs2 on pair1.value equals pair2.value
select new
{
Value = pair1.value,
Index1 = pair1.index,
Index2 = pair2.index
};
(你可以使用from pair2 in pairs2 where pair1.value == pair2.value
如果你願意......)
或非LINQ(使用Tuple<,,>
爲簡單起見,其他的選項是可行的):
var results = new List<Tuple<int, int, int>>();
for (int index1 = 0; index1 < list1.Count; index1++)
{
for (int index2 = 0; index2 < list2.Count; index2++)
{
if (list1[index1] == list2[index2])
{
results.Add(Tuple.Of(list1[index1], index1, index2);
}
}
}
注意,不同於一般的交集操作,這兩個可以給你相同的值的多個結果 - 因爲可以有多個索引對。例如,對於列表{ 1, 2 }
和{2, 2, 0}
,您將擁有(值= 2,索引1 = 1,索引2 = 0),(值= 2,索引1 = 1,索引2 = 1)的元組。
我剛剛使用這個答案從一個json字符串中創建一個新的對象,我從一個節點rest api消耗。這太棒了。再次感謝您節省@Jon Skeet的一天! –
試試下面的代碼
List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 };
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 };
var lstA_Temp = lstA.Select((value, index) => new { index, value }).ToList();
var lstB_Temp = lstB.Select((value, index) => new { index, value }).ToList();
List<int> result = (from A in lstA_Temp from B in lstB_Temp
where A.index == B.index where A.value == B.value
select A.value).ToList();
你也可以做這件事而不LINQ見下面的邏輯
List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 };
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 };
List<int> lstResult = new List<int>();
for (int i = 0; i < lstA.Count; i++)
{
if (lstA[i] == lstB[i])
lstResult.Add(lstA[i]);
}
請注意,如果您在索引上匹配,則使用'Zip' IMO會更簡單。 –
- 1. 從列表中獲取元素索引
- 2. 比較兩個列表並獲取相同元素的索引
- 3. 從列表中獲取最後一個元素不管索引
- 4. 從兩個列表中獲取所有元素的組合?
- 5. 獲取C++中的元素索引
- 6. 獲取Python中列表中最小N個元素的索引
- 7. 獲取兩個陣列中具有不同值的元素
- 8. 獲取列表的元素通過python中的每個索引?
- 9. PHP - 從數組中的某個索引中獲取元素,其中的某個元素具有一定的值
- 10. 從列表中獲取索引元素是否線程安全?
- 11. 如何從列表中獲取元素索引
- 12. 使用jQuery獲取列表中的索引元素
- 13. 獲取陣列中兩個元素之間的所有元素
- 14. 從列表列表中獲取索引
- 15. Python循環迭代獲取列表中元素的所有索引的列表
- 16. 列表中的「多個」索引元素
- 17. 獲取隊列c中元素的索引#
- 18. 使用Javascript/jQuery的從元素位/索引獲取的數組元素索引
- 19. 從div元素獲取列表索引id
- 20. 獲取特定於其中元素的子列表的索引
- 21. 獲取C#中的XSD元素列表
- 22. 獲取元素的索引在具有特定的子
- 23. 如何獲取Haskell列表中的元素索引
- 24. 從兩個數組中刪除具有相同索引的零元素
- 25. C - 從列表中檢索元素
- 26. 比較兩個陣列列表並獲取常用元素的位置
- 27. jQuery中獲取使用索引()的元素的索引
- 28. 如何在Excel中的兩個列表中獲取不常見的元素?
- 29. 列表中有多少元素,該元素的索引點擊
- 30. 在兩個具有其他id的div元素中有兩個具有相同id的元素是否正常?
你能告訴你的代碼,也表明一個例子嗎? –
你嘗試過什麼嗎?你當然可以用LINQ來做這件事,儘管我懷疑它的代碼和沒有代碼一樣多。 –
現在有兩個答案,其中一個只在值相同時才匹配*和*索引相同,其中一個只與值匹配(給每個匹配提供兩個索引)。你想要什麼? –