KevinH
KevinH

Reputation: 25

c # datatable replace duplicate values with blanks

I have a dataset like this. I would like to replace the repeating values with blanks like the second column. So only the first instance of the value is output and the others rows are blank.

current output
1       1
1 
1
1
2       2
2       
2
3       3
3
3
3
3
4       4
4
4
4

I started with this but the second time in the loop blank does not equal i-1 so I am kind of stuck.

for (int i = 1; i < dt.Rows.Count - 1; i++)
{
    // Compare with previous row using index
    if (dt.Rows[i]["Supplier_No"].ToString().Equals(dt.Rows[i - 1]["Supplier_No"].ToString()))
    {
        dt.Rows[i]["Supplier_No"] = "";
    }
}

Upvotes: 0

Views: 265

Answers (2)

jdweng
jdweng

Reputation: 34433

The following code is tested :

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;


namespace ConsoleApplication181
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Supplier_No", typeof(int));
            dt.Rows.Add(new object[] {1});
            dt.Rows.Add(new object[] {1});
            dt.Rows.Add(new object[] {1});
            dt.Rows.Add(new object[] {1});
            dt.Rows.Add(new object[] {1});
            dt.Rows.Add(new object[] {2});
            dt.Rows.Add(new object[] {2});
            dt.Rows.Add(new object[] {2});
            dt.Rows.Add(new object[] {2});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {3});
            dt.Rows.Add(new object[] {4});
            dt.Rows.Add(new object[] {4});
            dt.Rows.Add(new object[] {4});
            dt.Rows.Add(new object[] {4});
            dt.Rows.Add(new object[] {4});

            var groups = dt.AsEnumerable().GroupBy(x=> x.Field<int>("Supplier_No"));

            foreach (var group in groups)
            {
                for (int i = 1; i < group.Count(); i++)
                {
                    group.Skip(i).First()["Supplier_No"] = DBNull.Value;
                }
            }

        }

 
    }
   
 
}

Upvotes: -1

Rick Davin
Rick Davin

Reputation: 1041

You will need to remember what the original value was.

string previous = dt.Rows[0]["Supplier_No"].ToString();

for (int i = 1; i < dt.Rows.Count - 1; i++)
{
    // Compare with previous row using index
    if (dt.Rows[i]["Supplier_No"].ToString().Equals(previous))
    {
        dt.Rows[i]["Supplier_No"] = "";
    }
    else
    {
        previous = dt.Rows[i]["Supplier_No"].ToString();
    }
}

Upvotes: 2

Related Questions