问题描述
如果我有对象列表,并且我不想允许对象的某些属性重复。我的理解是,我可以使用distinctBy()删除其中一个对象。我的问题是如何选择保留哪些属性值相同的对象?
示例: 我将如何删除列表tm中所有具有“ year”重复值的对象,并保持具有“ someValue”最大值的对象?
class TestModel{
public int year{ get; set; }
public int someValue { get; set; }
}
List<TestModel> tm = new List<TestModel>();
//populate list
//I was thinking something like this
tm.distinctBy(x => x.year).Select(x => max(X=>someValue))
谢谢!
解决方法
您可以使用GroupBy
和Aggregate
(LINQ中没有IHttpClientFactory
内置方法)
.AddHttpClient()
,
使用GroupBy
/ SelectMany
模式和Take(1)
后跟OrderBy
的用户:
IEnumerable<TestModel> result =
tm
.GroupBy(x => x.year)
.SelectMany(xs =>
xs
.OrderByDescending(x => x.someValue)
.Take(1));
这是一个例子:
List<TestModel> tm = new List<TestModel>()
{
new TestModel() { year = 2020,someValue = 5 },new TestModel() { year = 2020,someValue = 15 },new TestModel() { year = 2019,someValue = 6 },};
那给了我