简体   繁体   English

C#跳过第一行,但希望它跳过最后一行

[英]C# Skips first row but want it to skip last row instead

Not sure if this is the best way but here's my code so far. 不确定这是否是最好的方法,但到目前为止这是我的代码。 Currently, it keeps the first duplicate and deletes the others from the table. 目前,它保留第一个副本并从表中删除其他副本。 I want it to keep the last row with the largest OrderId number and delete the rest. 我希望它保留最后一行具有最大的OrderId编号并删除其余部分。 I've tried Take instead of Skip but can't seem to get it working properly. 我试过Take而不是Skip但似乎无法让它正常工作。

var duplicateRow = (from o in db.Orders
                    group o by new { o.CustomerId } into results
                    select results.Skip(1)
                    ).SelectMany(a => a);

db.Orders.DeleteAllOnSubmit(duplicateRow);
db.SubmitChanges();

在此输入图像描述

Since you don't use OrderBy the result is arbitrary 由于您不使用OrderBy ,因此结果是任意的

I want it to keep the last row with the largest 'OrderId' number 我希望它保留最后一行的最大'OrderId'号

Then use: 然后使用:

var duplicateRows =  db.Orders
    .GroupBy(x => x.CustomerId)
    .SelectMany(g => g.OrderByDescending(o => OrderId).Skip(1));

You can use Reverse(): 你可以使用Reverse():

using System;
using System.Linq;

public class Program
{
    public class O
    {
        public int CustomerId;
        public int OrderId;
        public O(int c,int o) 
        {
            CustomerId = c; 
            OrderId = o;
        }

        public override string ToString() 
        {
            return string.Format("(C_ID: {0}, O_ID:{1})",CustomerId, OrderId);
        }
    }


    public static void Main()
    {
        var data = new O[]{ new O(1,1),new O(2,1),new O(3,1),new O(1,2)};

        var duplicateRow = (from o in data
                            group o by new { o.CustomerId } into results
                            select results.Reverse().Take(1) // reverse and then take 1
                           ).SelectMany(a => a);

        foreach( var o in duplicateRow)
                Console.WriteLine(o);

        Console.ReadLine();
    }
}

Output: 输出:

(C_ID: 1, O_ID:2)
(C_ID: 2, O_ID:1)
(C_ID: 3, O_ID:1)

This works due to stableness - if your input have later OrderID earlier you need to OrderBy as well. 这是因为稳定性 - 如果你的输入稍后有OrderID,你也需要OrderBy。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM