-3

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?

lynx
  • 45
  • 1
  • 7
  • 3
    what you have tried? – M.kazem Akhgary Jun 24 '15 at 16:09
  • `var dups = from row in _positionTable.Copy().AsEnumerable() group row by new { SubsystemTypeId = row.Field("Parent ID"), SupplierId = row.Field("ID") } into grp where grp.Count() > 1 select grp.Key;` – lynx Jun 24 '15 at 17:00

1 Answers1

0

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;
    }
}
SKG
  • 152
  • 5
  • @lynx...did you get an error? can you please post why it didn't work out.... I have not tested the code...just typed it :-) – SKG Jun 24 '15 at 19:36
  • no i didn't get an error it just didn't remove the duplicates lol ... no worries i made the script so that when it adds it will make sure that if there are such element with the parent ID and ID then sum it else put the qty. it seems to work. Thanks a lot for the effort :D – lynx Jun 24 '15 at 19:46
  • thanks @lynx for letting me know...any chance that the original list was actually not duplicate (trailing spaces in Parent Id or Id) ? I will try it when I get a chance... – SKG Jun 24 '15 at 21:30