我有兩個 int 型別串列。
firstlist = new List<int>() { 1, 4, 9, 14, 19, 24 };
secondlist = new List<int>() { 2, 3, 4, 19, 22, 23 };
我想找到 in 的常見專案,并為firstlist
insecondlist
中的相同專案提供相同的索引secondlist
。然后我希望 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;
}
}
uj5u.com熱心網友回復:
您可以使用 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;
}
uj5u.com熱心網友回復:
用 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]);
}
}
uj5u.com熱心網友回復:
我提出的解決方案說明了您的問題未指定的一些情況:
- 串列可能有不同的長度
- 串列可能有重復的常見專案
這些情況中的任何一種都可能導致先前解決方案的錯誤行為。
我已經包含了一個帶有一些測驗資料的 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)}");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482043.html
標籤:C#
下一篇:.net核心反序列化xml回應