- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
示例类:
public class Pallet
{
public int Id { get; set; }
public List<Location> Locations { get; set; }
}
public class Location
{
public int Id { get; set; }
}
鉴于此输入:
var input = new List<Pallet>
{
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 3 }
}
},
new Pallet
{
Id = 2,
Locations = new List<Location>
{
new Location { Id = 2 }
}
},
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 4 }
}
},
};
是否有一种很好的 LINQ 方法可以将重复项(在父集合和子集合中)折叠为与此等效的方法?
var output = new List<Pallet>
{
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 3 },
new Location { Id = 4 }
}
},
new Pallet
{
Id = 2,
Locations = new List<Location>
{
new Location { Id = 2 }
}
}
};
是的,我可以遍历集合并手动合并项目,但我很好奇 LINQ 是否会/可以提供更具表现力的东西。
最佳答案
您可以使用 GroupBy
将匹配的 ID 收集在一起,然后是 Select
创建新集合:
var output = input.GroupBy(pallet => pallet.Id)
.Select(grp => new Pallet {
Id = grp.Key,
Locations = grp.SelectMany(pallet => pallet.Locations).Distinct().ToList()
}).ToList();
上面的一个问题是 Distinct()
只有在类类型上才能正常工作,如果你为它提供 IEqualityComparer<Location>
,或者让“位置”类实现 IEquatable<Location>
(也覆盖 object.GetHashCode
):
public class Location : IEquatable<Location>
{
public int Id { get; set; }
public bool Equals(Location other)
{
//Check whether the compared object is null.
if (object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (object.ReferenceEquals(this, other)) return true;
return Id == other.Id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
或者,您可以只使用第二个 GroupBy
而不是所有的爵士乐在每个组中选择第一个位置:
var output = input.GroupBy(pallet => pallet.Id)
.Select(grp => new Pallet {
Id = grp.Key,
Locations = grp.SelectMany(pallet => pallet.Locations)
.GroupBy(location => location.Id)
.Select(location => location.First())
.ToList()
}).ToList();
关于c# - 有没有办法使用 LINQ 将重复项目的集合与其子集合合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25396414/
我以前使用过像 Netbeans 和 eclipse 这样的 IDE。 我在 friend 的电脑上下载了“Visual Studio Express 2013 for windows desktop
我正在尝试弄清楚如何在 GBA 大小的 EZ Flash 3 合 1 卡中对 PSRAM 进行编程。基本上重复 GBA Exploader 和其他程序所做的事情。 如果我选择一个 block 并对其进
Filter1=re.findall(r'',PageSource) Filter2=re.findall(r'',PageSource) Filter3=re.findall(r'(.*?).*?'
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许在 Stack Overflow 上提出有关通用计算硬件和软件的问题。您可以编辑问题,使其成为
我是一名优秀的程序员,十分优秀!