[英]C# How to give same index to common items in 2 lists
我有兩個 int 類型列表。
firstlist = new List<int>() { 1, 4, 9, 14, 19, 24 };
secondlist = new List<int>() { 2, 3, 4, 19, 22, 23 };
我想在secondlist
中找到secondlist
的常見項目,並為firstlist
中的相同項目提供相同的索引。 然后我希望 secondlist 像這樣排序: secondlist = { 2, 4 , 3, 22, 19 , 23 };
實際上我希望兩個列表中的常見項目具有相同的索引。
我可以用一些循環和 if 語句來做到這一點,但是當列表有越來越多的項目時,它需要很長的代碼。 例如,當每個列表有 3 個成員時:
firstlist = new List<int>() { 1, 4, 9 };
secondlist = new List<int>() { 2, 3, 4 };
for (int i = 0; i < firstlist.Count; i++)
{
{
if (firstlist.Contains(secondlist[i]) ))
{
if(secondlist[i]==4)
{
qs1 = secondlist[0];
secondlist[0]= secondlist[i];
secondlist[i] = qs1;
}
else if (secondlist[i] == 9)
{
qs1 = secondlist[1];
secondlist[1] = secondlist[i];
secondlist[i] = qs1;
}
else if (secondlist[i] == 14)
{
qs1 = secondlist[2];
secondlist[2] = secondlist[i];
secondlist[i] = qs1;
}
}
您可以使用 Lists Intersect 函數來獲取常用項。 然后相應地交換第二個列表中的數字。
var firstlist = new List<int>() { 1, 4, 9, 14, 19, 24 };
var secondlist = new List<int>() { 2, 3, 4, 19, 22, 23 };
var common = firstlist.Intersect(secondlist);
foreach (var n in common)
{
var fIndex = firstlist.FindIndex(f => f == n);
var sIndex = secondlist.FindIndex(s => s == n);
var temp = secondlist[fIndex];
secondlist[fIndex] = n;
secondlist[sIndex] = temp;
}
用 for 循環直接做
for (int i = 0; i < firstlist.Count; i++)
{
var index = secondlist.IndexOf(firstlist[i]);
if (index >= 0)
{
secondlist.RemoveAt(index);
secondlist.Insert(i, firstlist[i]);
}
}
我提出的解決方案說明了您的問題未指定的一些情況:
這些情況中的任何一種都可能導致先前解決方案的錯誤行為。
我已經包含了一個帶有一些測試數據的 Main 方法來涵蓋這些情況。
void Main()
{
var list1 = new List<int>() { 1, 4, 9, 14, 19, 24 };
var list2 = new List<int>() { 2, 3, 4, 19, 22, 23 };
var list3 = new List<int>() { 1, 4, 9, 14, 19, 4 };
var list4 = new List<int>() { 2, 3, 4, 19, 4, 23 };
var list5 = new List<int>() { 1, 4, 9, 14, 19 };
var list6 = new List<int>() { 2, 3, 4, 19, 4, 23 };
var list7 = new List<int>() { 1, 4, 9, 4, 6, 19, 4 };
var list8 = new List<int>() { 2, 3, 4, 19, 8, 4};
SortCommon(list1, list2);
SortCommon(list3, list4);
SortCommon(list5, list6);
SortCommon(list7, list8);
}
void SortCommon(List<int> first, List<int> second)
{
for (var i = 0; i < second.Count && i < first.Count; i++)
{
//We check for common items in a loop, as multiple common items of the same value
//should be sorted in order
for (var index = 0; index++ >= 0 ; )
{
index = second.IndexOf(first[i], index);
//Need to make sure that we check to see if the item at index has already been sorted
if (index >= 0 && second[index] != first[index])
{
second[index] = second[i];
second[i] = first[i];
break;
}
}
}
Console.WriteLine($"First: {string.Join(", ", first)}");
Console.WriteLine($"Second: {string.Join(", ", second)}");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.