我有 2 个列表:-
OrigFruitList.Add(new Fruit { Category = "Apple", SubCategory = "" });
OrigFruitList.Add(new Fruit { Category = "Apple", SubCategory = "Red Apple" });
OrigFruitList.Add(new Fruit { Category = "Apple", SubCategory = "Green Apple" });
OrigFruitList.Add(new Fruit { Category = "Orange", SubCategory = "" });
OrigFruitList.Add(new Fruit { Category = "Peach", SubCategory = "" });
OrigFruitList.Add(new Fruit { Category = "Grapes", SubCategory = "Green Grapes" });
OrigFruitList.Add(new Fruit { Category = "Grapes", SubCategory = "Black Grapes" });
OrigFruitList.Add(new Fruit { Category = "Bananas", SubCategory = "" });
NormalFruitList.Add(new Fruit { Category = "Apple", SubCategory = "" });
NormalFruitList.Add(new Fruit { Category = "Apple", SubCategory = "Red Apple" });
NormalFruitList.Add(new Fruit { Category = "Apple", SubCategory = "Green Apple" });
NormalFruitList.Add(new Fruit { Category = "Orange", SubCategory = "Blood Orange" });
NormalFruitList.Add(new Fruit { Category = "Orange", SubCategory = "Sweet Orange" });
NormalFruitList.Add(new Fruit { Category = "Peach", SubCategory = "" });
NormalFruitList.Add(new Fruit { Category = "Bananas", SubCategory = "" });
NormalFruitList.Add(new Fruit { Category = "Bananas", SubCategory = "Yellow Bananas" });
NormalFruitList.Add(new Fruit { Category = "Bananas", SubCategory = "Green Bananas" });
现在我希望合并第二个列表,如果可能的话,根据第一个列表使用 LINQ。
例如,Original 列表中只有 1 个 Orange 条目,我希望将 Normal 列表中的 2 个条目附加到 Original 列表。香蕉也是如此。
如何使用 LINQ 实现这一目标?
感谢您的帮助和时间
------------我希望达到的结果
//FinalResult
//Apple
//Red Apple
//Green Apple
//Orange
//Blood Orange
//Sweet Orange
//Peach
//Green Grapes
//Black Grapes
//Bananas
//Yellow Banans
//Green Bananas
最佳答案
试试这个:
var difference = NormalFruitList.Where(normFruit =>
!OrigFruitList.Exists(
origFruit => origFruit.Category == normFruit.Category
&& origFruit.SubCategory == normFruit.SubCategory));
// If new Category is found in NormalFruitList it will be added to the end
int index = 0;
var result = new List<Fruit>(OrigFruitList);
foreach (var item in difference.Reverse())
{
index = result.IndexOf(OrigFruitList.FirstOrDefault(fruit => fruit.Category == item.Category));
result.Insert(index == -1 ? OrigFruitList.Count : index + 1, item);
}
关于c# - 使用 LINQ 从两个其他列表中填充单个列表而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526497/