Arvayne Arvayne - 1 year ago 40
C# Question

How do I check the values retrieved from this Linq query as .ToLower()?

This is my code:

DataRow r = VirtualTable
.FirstOrDefault(tt => (tt.Field<string>("Column1") == value1) ||
(tt.Field<string>("Column1") == value2));

This code retrieves a data row whose 'Column1' matches a given string. I then check this against a bool if statement. However, though I can change my string's capitalization, I don't know how to handle it with the value Linq gives me. Still learning linq, so I don't know my way around it yet.

In short, I have the string "Red box" in the table, but want it to be read as "red box" so it will match my internal string of the same value.

Additionally, I was trying to retrieve the
the row this query gives me, but I'm always retrieving a -1 even if it finds a match.

Here's the code to retrieve it:

int SelectedIndex = VirtualTable.Rows.IndexOf(r);

Answer Source

Try string.Equals to ignore case and overload Select to get row's index:

   var row = VirtualTable
     .Select((tt, index) => new {
        value = tt.Field<string>("Column1"),
        index = index})
     .FirstOrDefault(item => 
        string.Equals(item.value, value1, StringComparison.OrdinalIgnoreCase) ||
        string.Equals(item.value, value2, StringComparison.OrdinalIgnoreCase));

   // If we have the row found, we can get
   if (row != null) {
     var r = row.value;              // value, e.g. "bla-bla-bla"
     int selectedIndex = row.index;  // as well as its index, e.g. 123 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download