开发者

DataTable Filter From Code Side C#

开发者 https://www.devze.com 2023-03-12 15:20 出处:网络
I have a DataTable which I get by an upload of CSV document from the user and has columns, rows like that:

I have a DataTable which I get by an upload of CSV document from the user and has columns, rows like that:

Email      Age      Team
x@x.com    25       BarcelonaFC
y@y.com    32       BesiktasJK
z@z.com    18       Napoli
y@y.com    19       Boca Juniors
x@开发者_JS百科x.com    36       Internazionale

I need to filter that datatable before I insert it into the database. Email column should be unique. So I need to filter that datatable so that I get as a result eliminating 2 rows. I do not want to use LINQ, but if it is only solution, its ok.

Email      Age      Team
x@x.com    25       BarcelonaFC
y@y.com    32       BesiktasJK
z@z.com    18       Napoli


You can create a HashSet<string> holding email addresses, then loop backwards through the table, add the email address for each row to the hashset, and, if it's already there (if Add returns false), remove the row.


You can try something like this....

var dt = new DataTable();
dt = yourCurrentDataTable.DefaultView.ToTable(true, "Email", "Age", "Team");


You can use Dictionary for it:

First of all, you can create simple class:

class Data
{
  public int Age;
  public string Team;
}

After that you can insert your data to dictionary:

Dictionary<string, MyData> dic = new Dictionary<string, MyData>();
foreach(DataRow row in YourDataTable)
{
  if(!dic.ContainsKey(row[.. email ..])) 
  {
    dic.Add(..., ...);
  }
}

Now your dictionary ready to go...

0

精彩评论

暂无评论...
验证码 换一张
取 消