简体   繁体   English

如何将从此Linq查询中检索到的值检查为.ToLower()?

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

This is my code: 这是我的代码:

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

This code retrieves a data row whose 'Column1' matches a given string. 此代码检索“Column1”与给定字符串匹配的数据行。 I then check this against a bool if statement. 然后我对bool if语句进行检查。 However, though I can change my string's capitalization, I don't know how to handle it with the value Linq gives me. 但是,尽管我可以更改字符串的大小写,但我不知道如何使用Linq给我的值来处理它。 Still learning linq, so I don't know my way around it yet. 还在学习linq,所以我还不知道我的方式。

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. 简而言之,我在表中有字符串“Red box”,但希望它被读作“红色框”,因此它将匹配相同值的内部字符串。

Additionally, I was trying to retrieve the IndexOf the row this query gives me, but I'm always retrieving a -1 even if it finds a match. 另外,我试图检索此查询给我的行的IndexOf ,但即使找到匹配,我也总是检索​​-1。

Here's the code to retrieve it: 这是检索它的代码:

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

Try string.Equals to ignore case and overload Select to get row's index: 尝试使用string.Equals忽略大小写和重载Select以获取行的索引:

   var row = VirtualTable
     .AsEnumerable()
     .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 
     ... 
   }

You can use String.Equals(string,StringComparisonOption) to compare two strings using case-insensitive comparison. 您可以使用String.Equals(string,StringComparisonOption)来比较两个字符串,使用不区分大小写的比较。 This avoids generating yet-another-temporary-string as ToLower() would do, eg: 这样可以避免像ToLower()那样生成另一个临时字符串,例如:

tt.Field<string>("Column1").Equals(value1,StringComparison.OrdinalIgnoreCase)

or 要么

tt.Field<string>("Column1").Equals(value1,StringComparison.CurrentCultureIgnoreCase)

Make sure you use the appropriate comparison option. 确保使用适当的比较选项。 Different cultures have different casing rules. 不同的文化有不同的套管规则。 Ordinal is the fastest option as it compares strings using binary rules. Ordinal是最快的选择,因为它使用二进制规则比较字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM