1

我想知道在 LINQ 中是否有可能实现以下目标:

newList: { [1], [2] }
oldList: { [2], [3], [4], [5] }
resultantList = { [1], [2, 2], [3], [4], [5] }

好吧,那是过于简单化了。让我们说:

Class A
{
    public string Name;
    public IList<B> Items;
    public bool Equals(A obj)
    {
         return obj.Name == Name;
    }
}


newList<A> = {{ Name = "A", Items[1]}, { Name = "B", Items[1] }}
oldList<A> = {{ Name = "C", Items[2]}, { Name = "A", Items[2] }, { Name = "D", Items[1] }, { Name = "E", Items[1] },}
mergedList<A> = {{ Name = "A", Items[3]}, { Name = "B", Items[1]}, { Name = "C", Items[2]}, { Name = "D" , Items[1]}, { Name = "E" , Items[1]}}

请注意,对于 Name="A" 的实例,该列表实际上是两个列表的合并列表。顺序无关紧要,实际上平等更复杂。

我希望在类型上实现这一点(即以下工作,但效率低下):

var fragments = newGeometryFragments.Except(oldGeometryFragments).ToList();
fragments.AddRange(oldGeometryFragments.Except(newGeometryFragments).ToArray());
var mergedFragments = (from newGeometry in newGeometryFragments
                       from oldGeometry in oldGeometryFragments
                       where newGeometry.Equals(oldGeometry)
                       select MergeGeometryFragments(newGeometry, oldGeometry)).ToArray();
 fragments.AddRange(mergedFragments);
4

2 回答 2

1

您可以使用以下代码,假设您已经填写了oldList和:newList

newList.Union(oldList) // unite the collections
   .GroupBy(x => x /*, ComparerInstance*/) // will group by unique elemens
   .Select(x => x.ToList()) // or .ToArray(), convert each group to array or list
   .ToList(); // return a list of lists/arrays

上面的代码将生成一个集合列表。每个集合将有一个或多个相等的元素,具体取决于该元素在 中出现的次数newList.Union(oldList)

如果您正在使用特定元素并希望控制它们的比较方式(确定为相等),请将自定义IEqualityComparer<YourType>实例传递给该GroupBy方法。

于 2013-05-08T12:19:28.500 回答
0

您可以使用外部联接:

var oldList = new List<int?> { 2, 3, 4, 5 };
var newList = new List<int?> { 1, 2 };
var result = from all in oldList.Union(newList).OrderBy(num => num)
             join o in oldList on all equals o into gjOld
             from oldOuter in gjOld.DefaultIfEmpty()
             join n in newList on all equals n into gjNew
             from newOuter in gjNew.DefaultIfEmpty()
             select new { newVal = newOuter, oldVal = oldOuter };

当您实现EqualsGetHashCode/或实现 custom时,这也适用于自定义类IEqualityComparer<T>。那么Nullable<int>技巧也是不必要的

演示

newVal: 1   oldVal: 
newVal: 2   oldVal: 2
newVal:     oldVal: 3
newVal:     oldVal: 4
newVal:     oldVal: 5
于 2013-05-08T12:27:06.200 回答