C# Datatable Duplicate in LiNQ

148 views Asked by At

I have a Datatable with 4 columns:

Parent ID    ID    Qty    Qty Type
A            A12   5      xxx
B            A32   10     xxx
A            A12   4      xxx
A            B23   3      yyy

The end result should be:

Parent ID    ID    Qty    Qty Type
A            A12   9      xxx
B            A32   10     xxx
A            B23   3      yyy

So basically the logic should be it'll remove any set of {Parent ID AND ID} being the same and add the Qty to it. In our example the 1st and 3rd element are the same Parent ID and same ID so we remove the 3rd element and add the Qty to the first element (we also have to check if the QTY Type is the same if not we have to shoot out an error).

Notice how 1st and 4th did not get added - because their parent ID might be the same but their parent ID + ID are not the same therefore we don't add.

Is there a way to do this in Linq? not entirely but mostly with it?

1

There are 1 answers

3
SKG On BEST ANSWER

haven't tested it but see if this works...

void Main()
{
    var lst = dt.Rows.OfType<DataRow>()
                .GroupBy (r => r["Parent ID"].ToString() + "|" + r["ID"].ToString())
                .Select (g => Record.GenerateRecord(g))
                .ToList();

}


public class Record
{
    public string ParentId { get; set; }
    public string Id { get; set; }
    public int Qty { get; set; }
    public string QtyType { get; set; }

    public static Record GenerateRecord(IGrouping<string, DataRow> grp)
    {
        var splt=grp.Key.Split('|'); 
        var rec= new Record{Parent=splt[0], Id=splt[1], QtyType=grp.First()["Qty Type"].ToString()};
        if (grp.Count()==1)
            rec.Qty = int.Parse(grp.First()["Qty"].ToString());
        else
            rec.Qty = grp.Sum (g => int.Parse(g["Qty"].ToString()));
        return rec;
    }
}