akd
akd

Reputation: 6758

How to Filter a DataView by another datatable row attribute

I have 2 methods that I do not have any control over.

One returns me all dates with needed unique code(one of the row column row[code]) as DataView.

 DataView allDatesWithCode= portal.GetAllDatesWithCode();

And another method returns me only available dates but without the code.

DataTable availableDates = portal.GetAvailableDates();

Both allDatesWithCode and availaleDates has a common date column (row[date]).

How can I filter allDatesWithCode with availableDates to have only available dates with code?

DataView availableDatesWithCode = allDatesWithCode // (filtered by available date).

And If I had control over the portal.GetAllDatesWithCode() and portal.GetAllDatesWithCode would it make it better to have both as DataTable or DataView? enter image description here

Upvotes: 1

Views: 1759

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82474

You can use a StringBuilder to create a RowFilter for your DataView:

StringBuilder RowFilter = new StringBuilder("date IN(");
foreach(DataRow dr in availaleDates.Rows) {
    RowFilter.Append(dr["date"].ToString()).Append(",");
}
allDatesWithCode.RowFilter = RowFilter.ToString().TrimEnd(',') +")";

If you had control over those methods then I suggest returning a DataTable and not a DataView, and also create a new method that will give you only the rows you need in the first place.

Upvotes: 0

dotNET
dotNET

Reputation: 35400

Use LINQ to join the two collections on the common field. This will give you a projection that contains all 3 fields (1 field of the DataTable and 2 fields of the DataView) for only the rows that exist in both collections (as you are joining them). You can then use Select to project this further to have only 2 fields. An example would be:

var res = (
              from dtr in DT.AsEnumerable()
              join DataRowView dvr in allDatesWithCode on dtr["date"] equals dvr["date"]
              select new {Date = dtr.Field<DateTime>("date"), Code = ((DataRowView)dvr).Row.Field<string>("code") }
          ).ToArray();

res is now an array of anonymous type objects (for all rows that exist in both collections). Each anonymous object has Date and Code properties. You can create you own type for storing the results as well.

Upvotes: 1

Related Questions