假设我有此价格类型列表:
CLASSPATH
我需要删除所有价格相同的商品,但前提是该商品是list元素的同级商品。是否可以使用LINQ来实现这一目标?
我的预期输出是
[
{
"Id": 57571,
"Price": 1745.0,
"DateAdded": "2018-12-01T00:00:00"
},
{
"Id": 67537,
"Price": 1695.0,
"DateAdded": "2018-09-24T00:00:00"
},
{
"Id": 80042,
"Price": 1645.0,
"DateAdded": "2019-03-24T00:00:00"
},
{
"Id": 155866,
"Price": 1545.0,
"DateAdded": "2019-04-24T00:00:00"
},
{
"Id": 163643,
"Price": 1545.0,
"DateAdded": "2019-04-26T00:00:00"
},
{
"Id": 171379,
"Price": 1545.0,
"DateAdded": "2019-04-27T00:00:00"
},
{
"Id": 178990,
"Price": 1545.0,
"DateAdded": "2019-04-28T00:00:00"
}
]
我完全不知道如何实现这一目标。我感谢任何建议。
答案 0 :(得分:3)
通过使用Microsoft C#文档中的ChunkBy
extension方法,您可以
myData.ChunkBy(x => x.Price).Select(g => g.First())
...或通过使用MoreLinq's GroupAdjacent
您可以
myData.GroupAdjacent(x => x.Price).Select(g => g.First())
答案 1 :(得分:2)
您可以简单地使用迭代器来这样做:
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var input = new[] { 1, 2, 2, 3, 4, 4, 3, 2, 2, 1 };
var output = GetUniqueAdjacent(input);
foreach (var o in output)
{
Console.WriteLine(o);
}
}
public static IEnumerable<int> GetUniqueAdjacent(IEnumerable<int> input)
{
bool first = true;
int previous = -1;
foreach (var i in input)
{
if (first)
{
previous = i;
yield return i;
first = false;
continue;
}
if (i == previous)
{
previous = i;
continue;
}
previous = i;
yield return i;
}
}
}
这将输出1, 2, 3, 4, 3, 2, 1
,仅在重复项相邻时将其删除。
答案 2 :(得分:0)
这可以通过常规的Where
调用来完成。
int? previousPrice = null;
var output = myData.Where(d => {
var result = !previousPrice.HasValue || previousPrice.Value != d.Price;
previousPrice = d.Price;
return result;
}).ToList();