我正在尝试从 2 个现有列表(A、B)创建 3 个不同的列表(1、2、3)。
这 3 个列表需要确定以下关系。
- 列表 1 - 列表 A 中但不在列表 B 中的项目
- 列表 2 - 列表 B 中但不在列表 A 中的项目
- 列表 3 - 两个列表中的项目。
然后我想将所有列表合并为一个列表。
我的问题是我想通过添加一个枚举来识别差异,该枚举识别每个列表的项目之间的关系。但是通过添加 Enum,Except
Linq 函数无法识别(显然)列表相同的事实。因为 Linq 查询不同,所以我无法通过更改语句的顺序来解决这个问题,即。识别列表,然后添加枚举。
这是我必须的代码(不能正常工作)
可能有更好的方法。
List<ManufactorListItem> manufactorItemList =
manufactorRepository.GetManufactorList();
// Get the Manufactors from the Families repository
List<ManufactorListItem> familyManufactorList =
this.familyRepository.GetManufactorList(familyGuid);
// Identify Manufactors that are only found in the Manufactor Repository
List<ManufactorListItem> inManufactorsOnly =
manufactorItemList.Except(familyManufactorList).ToList();
// Mark them as (Parent Only)
foreach (ManufactorListItem manOnly in inManufactorsOnly) {
manOnly.InheritanceState = EnumInheritanceState.InParent;
}
// Identify Manufactors that are only found in the Family Repository
List<ManufactorListItem> inFamiliesOnly =
familyManufactorList.Except(manufactorItemList).ToList();
// Mark them as (Child Only)
foreach (ManufactorListItem famOnly in inFamiliesOnly) {
famOnly.InheritanceState = EnumInheritanceState.InChild;
}
// Identify Manufactors that are found in both Repositories
List<ManufactorListItem> sameList =
manufactorItemList.Intersect(familyManufactorList).ToList();
// Mark them Accordingly
foreach (ManufactorListItem same in sameList) {
same.InheritanceState = EnumInheritanceState.InBoth;
}
// Create an output List
List<ManufactorListItem> manufactors = new List<ManufactorListItem>();
// Join all of the lists together.
manufactors = sameList.Union(inManufactorsOnly).
Union(inFamiliesOnly).ToList();
有什么想法可以解决这个问题吗? 提前致谢
最佳答案
你可以让它更简单:
List<ManufactorListItem> manufactorItemList = ...;
List<ManufactorListItem> familyManufactorList = ...;
var allItems = manufactorItemList.ToDictionary(i => i, i => InheritanceState.InParent);
foreach (var familyManufactor in familyManufactorList)
{
allItems[familyManufactor] = allItems.ContainsKey(familyManufactor) ?
InheritanceState.InBoth :
InheritanceState.InChild;
}
//that's all, now we can get any subset items:
var inFamiliesOnly = allItems.Where(p => p.Value == InheritanceState.InChild).Select(p => p.Key);
var inManufactorsOnly = allItems.Where(p => p.Value == InheritanceState.InParent).Select(p => p.Key);
var allManufactors = allItems.Keys;
关于c# Linq 延迟执行挑战 - 创建 3 个不同列表所需的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5350166/