下面是我的模型:獲取不適當的排名,同時合併和安排2列表
public class Test
{
public int TestId { get; set; }
public List<VariantsRank> VariantsRanks { get; set; }
}
public class VariantsRank
{
public int VariantId { get; set; }
public string Name { get; set; }
public int Rank { get; set; }
}
我有現成的Test
實例,它包含VariantsRanks
VariantId = 10, Name = "V1", Rank = 0
VariantId = 11, Name = "V2", Rank = 1
以下值然後我需要合併以下VariantsRank
VariantId = 12, Name = "V3", Rank = 0
VariantId = 13, Name = "V4", Rank = 1
並增加Rank
產生以下輸出
VariantId = 10, Name = "V1", Rank = 0
VariantId = 11, Name = "V2", Rank = 1
VariantId = 12, Name = "V3", Rank = 2
VariantId = 13, Name = "V4", Rank = 3
我用下面的代碼工作正常(List1
是原來的列表,List2
是列表被合併)
int highestOrder = (List1.VariantsRanks.Max(cpo => cpo.Rank)) + 1;
foreach (var rank in List2.VariantsRanks)
{
var match = List1.VariantsRanks.FirstOrDefault(x => x.VariantId == rank.VariantId);
if (match != null) // found
{
match.Rank = rank.Rank;
}
else
{
rank.Rank = highestOrder;
highestOrder = highestOrder + 1;
List1.VariantsRanks.Add(rank);
}
}
我那麼需要將以下VariantsRank
合併到新列表中(請注意匹配的VariantId
值,但它們的順序相反)
VariantId = 13, Name = "V4", Rank = 0
VariantId = 12, Name = "V3", Rank = 1
從而使輸出應該是
VariantId = 10, Name = "V1", Rank = 0
VariantId = 11, Name = "V2", Rank = 1
VariantId = 13, Name = "V4", Rank = 2
VariantId = 12, Name = "V3", Rank = 3
但是上面的代碼,而不是輸出
VariantId = 10, Name = "V1", Rank = 0
VariantId = 11, Name = "V2", Rank = 1
VariantId = 12, Name = "V3", Rank = 1
VariantId = 13, Name = "V4", Rank = 0
和Rank
值不正確地遞增
如何修改代碼,以確保未添加重複的VariantId
,但增加了Rank
?
您的代碼需要在問題中,而不是鏈接到小提琴 –
@StephenMuecke:實際上,這將增加我的問題的長度和提供小提琴的原因,因爲它可以很容易地直接看到輸出並直接使用Enigmativity指出的代碼。長問題沒有引起注意 –
將現有代碼縮減爲每個列表2個項目並顯示代碼在哪裏操作列表 - 這是重要的(並且小提琴甚至不工作 - 它的超時) –