Let's see if you can help me. I'm not very good at LINQ, so I don't even know if it is possible. Actually, I think it is, but I couldn't find yet the best way to do it.
I have an object that has a List and a DataTable. This DataTable has the same amount of rows as the amount of items in the list, and they're correlated (first item in the list is related to first row, second item to second row and so it goes). I want to be able to select a date range and its related rows from the DataTable. I'm currently doing it, but it has some loops and an IndexOf, and it is taking me a long time to process. Do you guys have any suggestion on how I can make it faster?
This is basically the structure of the object (I've simplified a bit, but what matters is here):
public class CustomObject(){
public List<DateTime> dates { get; set; }
public DataTable table { get; set; }
}
And here is how I'm selecting over it:
private bool SelectRange(DateTime begin, DateTime end, CustomObject custom)
{
var range = from date in custom.dates
where date.CompareTo(begin) >= 0 &&
date.CompareTo(end) < 0
select date;
DataTable tmpTable = custom.table.Copy(); // I'm doing this just to copy the structure of the DataTable
tmpTable.Clear();
if (range.Count() > 0)
{
List<DataRow> rowList = new List<DataRow>();
foreach (var date in range)
{
int dateIndex = custom.dates.IndexOf(date);
rowList.Add(custom.table.Rows[dateIndex]);
}
foreach (DataRow row in rowList)
{
tmpTable.Rows.Add(row.ItemArray);
}
custom.table = tmpTable;
}
else
{
custom.table.Rows.Clear();
}
}
Do you have any ideas on how to optimize this?
Thanks a lot for your attention. Any ideas will be very welcome (corrections on my non-native English will be welcome too).