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
?
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.