2

See the picture of sample results that I need to parse

See the C# Datatable's values above. I need to get the highlighted value, based on colA, and dateof, which I could explain with SQL, like this:

SELECT TOP 1 colB FROM dt WHERE colA = 'aaa' ORDER BY dateof ASC

I have to do it in C#, not in SQL.

How can I get that value?

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Ash
  • 1,269
  • 3
  • 25
  • 49

1 Answers1

4

Can you please try the following code and let me know whether it helps or not? Let myDataTable,be the DataTable that you are processing, assume that the type of field is string(change appropriately if needed)

myDataTable.AsEnumerable()
           .Where(x => x.Field<string>("colA") == "aaa")
           .OrderBy(y => y.Field<string>("dateof"))
           .Take(1)
           .Select(s => s.Field<string>("colB"))

Or else this may help you:

var defaultSelectedRow = myDataTable.AsEnumerable()
                                    .Where(x => x.Field<string>("colA") == "aaa")
                                    .OrderBy(y => y.Field<string>("dateof")).FirstOrDefault();
if (defaultSelectedRow != null)
{
    string colBValue = defaultSelectedRow.Field<string>("colB");
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • 1
    The second one is perfect. Thank you for your help. I have seen the "select" part in a few places, I have seen the "take(1)" part in a few places, and I have seen the DataTable ordering in a few places, but your answer has all of them together. Great help! – Ash Aug 29 '18 at 11:27