Reputation: 952
I have DataTable with data as below,
Couponid STATE
20160406000033 A
20160406000051 A <--- I don't want this row
20160406000051 K
20160406000051 K
And I have a List list_coupon which include 20160406000051.
Now, I want to copy the whole DataTable only excluding rows which match the List list_coupon and have 'A' value simultaneously. If the Couponid matches the list and value is 'K', it has to stay in DataTable.
To explain in another way,
While processing every row,
if a row doesn't belong to the list, this row has to stay in DataTable.
However, if a row belongs to the list, and if the row has 'A' value, this row has to be excluded but other rows belonging to the list with 'K' value have to stay in DataTable.
I did this by using couples of loop but it took too much time..
And I think below code which I tried divides the DataTable as rows belong to the list or not whereas I need rows which 'both belong and doesn't belong' to the list as well..
IEnumerable<DataRow> rows_query = from r in dt.AsEnumerable()
where !list_coupon.Contains(r.Field<string>("Couponid")) &&
r.Field<string>("STATE") != "A"
select r;
dt = rows_query.CopyToDataTable();
Your excellent advice will be highly appreciated !
Thank you so much !
Upvotes: 0
Views: 1324
Reputation: 3319
Just change the query to
IEnumerable<DataRow> rows_query = from r in dt.AsEnumerable()
where !(list_coupon.Contains(r.Field<string>("Couponid")) &&
r.Field<string>("STATE") == "A")
select r;
dt = rows_query.CopyToDataTable();
Keep the not operator out of both and it will work smoothly .
Hope it will help you.
Upvotes: 2
Reputation: 18127
So from your explanation I understood you want every row which is not in the list OR is in the list but with value different from A.
You need to use or operator in linq ||
.
IEnumerable<DataRow> rows_query = from r in dt.AsEnumerable()
where !list_coupon.Contains(r.Field<string>("Couponid")) ||
(list_coupon.Contains(r.Field<string>("Couponid")) &&
r.Field<string>("STATE") != "A")
select r;
if(rows_query.Any())
dt = rows_query.CopyToDataTable();
It is good to check if there is any rows, because CopyToDataTable()
will throw exception if no rows are returned from the linq.
Upvotes: 1