簡體   English   中英

需要有關C#LINQ List聚合表達式的建議

[英]Need advice for C# LINQ List aggregation expression

假設我有以下類型的價格列表:

[
    {
        "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"
    }
]

我需要刪除所有價格相同的商品,但前提是該商品是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"
    }
]

我完全不知道如何實現這一目標。 我感謝任何建議。

通過使用Microsoft C#文檔中的ChunkBy擴展方法,您可以

myData.ChunkBy(x => x.Price).Select(g => g.First())

...或者通過使用MoreLinq的GroupAdjacent您可以

myData.GroupAdjacent(x => x.Price).Select(g => g.First())

您可以使用迭代器簡單地做到這一點:

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僅在重復項相鄰時將其刪除。

這可以通過常規的Where調用來完成。

int? previousPrice = null;

var output = myData.Where(d => {
  var result = !previousPrice.HasValue || previousPrice.Value != d.Price;
  previousPrice = d.Price;
  return result;
}).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM