0

I have a dotnetfiddle in which I show my data https://dotnetfiddle.net/UK2ZNX

I don't mind having a linq statement to group my data into an array , but I want to end up with a for loop (not foreach) for simplicity on looping over my data and when finding the duplicates stored in say an array, then I can manipulate them a bit

for(int i = 0; i < table1.Rows.Count; i++)
{
    Console.WriteLine("ID="+table1.Rows[i][0] + "  Name=" + table1.Rows[i][2]);

    //troublecalls.Add(TroubleCallModel.CreateTroubleCallFromRow(myDT.Rows[i]));
}

I was trying to store some data in Hashset

HashSet<int> hs = new HashSet<int>();  

but I don't think that was helping me

Based on my dotnetfiddle output

I have duplicate ID of 23 and 44 and 64

Instead of seeing

ID = 44 Name = Fido
ID = 44 Name = Thad

I want to combine and see

ID = 44  Name = Fido, Thad

Likewise for any duplicates ( currently in dotnetfiddle are also 23 and 64)

Reason for the wanting a for loop is that I have like 30 columns in my real data and I want to be able to remove / change / not show etc.. other columns

Just not sure what the best approach is

1 Answers1

1

You were on the right idea, but use a dictionary instead. The ID will be the key. Check if dictionary does not have the key, if it doesn't, add the key value pair, if it does, append Name to the end of the current entry.

A very simple example:

Dictionary<int, string> myDic = new Dictionary<int, string>();

for (int i = 0; i < table1.Rows.Count; i++)
{
     if (myDic.ContainsKey(table1.Rows[i][0]))
     {
          myDic[table1.Rows[i][0]] += $", {table1.Rows[i][2]}";
     }
     else
     {
          myDic.Add(table1.Rows[i][0], table1.Rows[i][2]);
     }
}

If you want them to be a data structure, do the above, just with a custom class that holds those values, and since you want LINQ, use Any() and then append/add the element.

Dispersia
  • 1,436
  • 9
  • 23
  • I'm not sure that I want Linq as when I can have many columns and lots of manipulation on what i want to omit, append and change I am feeling that linq is harder (at least for me) So with a dictionary, how can I start to store the values? –  Jan 11 '16 at 17:27
  • I added a very basic example. Note: It's C#6, if you're using an older version, just change the string interpolation to just a plus. – Dispersia Jan 11 '16 at 17:39
  • $ ? string interpolation? I seem to have a issues with my dotnetfiddle with https://dotnetfiddle.net/UK2ZNX object to int and object to string –  Jan 11 '16 at 17:44
  • Hi, I really need to loop over my datatable instead as I have a lot of columns in my real data in which this is causing a problem http://stackoverflow.com/questions/34731207/combining-datatable-duplicated-items-with-a-dictionary-and-getting-issue-with-du –  Jan 11 '16 at 21:15