下面創建列表是我的課:試圖從兩個列表
public class Test
{
public int TestId { get; set; }
public List<VariantsRank> VariantsRanks { get; set; }
}
public class VariantsRank
{
public string Name { get; set; }
public int Rank { get; set; }
}
以下2種方法:
testList的var testList = CreateDataFromList();//return List<Test>
Var testListfromDb = GetDatafromDB();//return List<Test>
記錄:
testListfromDb的[0] : 100
List of VariantRanks
[1]: 101
List of VariantRanks
記錄:
[0] : 100
List of VariantRanks // Order of variants will be different here and that is important to me
[1]: 101
List of VariantRanks // Order of variants will be different here and that is important to me
下面是我的變量,我想最後的輸出:
var final = new List<Test>();
方案:
)
testList = 100 and 101
testListfromDb = 101
Expected Output for 1st scenario : final = 100 and 101(2 records and this 101 record will be from testListfromDb)
)
testList = 100 and 101
testListfromDb = 100
Expected Output for 2nd scenario : final = 100 and 101(2 records and this 100 record will be from testListfromDb)
)
testList = 100 and 101
testListfromDb = 100 and 101
Expected Output for 3rd scenario : final = 100 and 101 (2 records and both will be from testListfromDb)
我已經做了3次的情況,但我沒有得到如何解決第一和第二方案。
代碼:
var final = new List<Test>();
var testList = CreateDataFromList(list); //return List<Test>
Var testListfromDb = GetDatafromDB();//return List<Test>
if (testListfromDb == null)
final = testList;
else
{
if (testList.Count == testListfromDb.Count) // 3rd scenario
final = testListfromDb;
}
更新:
public void Method()
{
var testList = new List<Test>();
testList.Add(new Test { TestId = 100 });
testList.Add(new Test { TestId = 101 });
var testListfromDb = new List<Test>();
var final = new List<Test>();
//scenario 1
testListfromDb.Add(new Test { TestId = 101 });
//expected output in final variable
final[0] = testList[0];
final[1] = testListfromDb[0];
//scenario 2
testListfromDb.Add(new Test { TestId = 100 });
//expected output in final variable
final[0] = testListfromDb[0];
final[1] = testList[1];
//scenario 3
testListfromDb.Add(new Test { TestId = 100 });
testListfromDb.Add(new Test { TestId = 101 });
//expected output in final variable
final[0] = testListfromDb[0];
final[1] = testListfromDb[1];
}
如果您有兩個列表,首先比較列表的大小,使最大列表成爲最終列表。然後循環添加第二個列表,添加最終列表中尚未包含的項目? – JohnG
我認爲你是否贊成非答覆? –
Downvoter請給出downvoting的原因,因爲它會幫助我和其他人在提問時再犯錯誤:) –