nnnn
nnnn

Reputation: 1051

Checking one column with same data for reading csv file in C#.net

I realize this is a newbie question, but I'm looking for a simple solution.

I loaded a csv file into DataTable. Let my CSV contains four columns (ColorCode, SirtID, StartDate, EndDate) like this:

#ffffff,s0012,2011/05/01,2011/05/11
#ffffff,s0013,2011/05/03,2011/05/10
#ffffff,s0022,2011/06/01,2011/06/11
#ffffff,s0032,2011/05/01,2011/05/12

I want to return an error message if CSV file contained two or more different ColorCodes like this:

#ffffff,s0012,2011/05/01,2011/05/11 
#ffffff,s0013,2011/05/03,2011/05/10
#ffffff,s0022,2011/06/01,2011/06/11
#000000,s0032,2011/05/01,2011/05/12

What's the best way to check whether CSV file contained only one ColorCode?

Upvotes: 0

Views: 375

Answers (2)

FIre Panda
FIre Panda

Reputation: 6637

You could do

 DataTable dt = new DataTable();
    .....
    ....
   if(dt.Rows.Count > 0)
     if(dt.Select("ColorCode <> " + dt.Rows[0]["ColorCode"].ToString()).Length > 0)
       throw new Exception("Two or more different ColorCodes exists");

Upvotes: 1

as-cii
as-cii

Reputation: 13029

You could use LINQ:

var query = myTable.AsEnumerable();
// Assuming there is one value at least.
var first = query.First().Field<string>("ColorCode");
if (query.Any(a => a.Field<string>("ColorCode") != first))
{
    throw new Exception();
}

Upvotes: 2

Related Questions