12

I have a data table and I want to perform a case insensitive group by over a column of data table (say Column1 of type string). I observed that normally LINQ to DataSet performs a case sensitive comparison. For example, if Column1 has two string values "Test" and "test", after applying group by it returns two separate rows with the values "Test" and "test", instead of one.

The query is:

var countGroupQuery = from table in dataTable.AsEnumerable()
                      group table by table.Field<string>(Column1) into groupedTable
                      select new
                      {
                          value = groupedTable.Key,
                          count = groupedTable.Count()
                      };

Is there any method to perform a case-insensitive group by so that in the above example I get only one row with one value (either "Test" or "test")? ToUpper or ToLower would actually change the values to either upper case or lower case instead of using at least one of the input values, so I don't want to use this:

group table by table.Field<string>(Column1).ToUpper() into groupedTable
4

3 に答える 3

23

クエリ式からこれを行うことはできませんが、ドット表記で行うことができます。

var query = dataTable.AsEnumerable()
                     .GroupBy(x => table.Field<string>(Column1),
                              StringComparer.InvariantCultureIgnoreCase)
                     .Select(groupedTable => new
                             {
                                 value = groupedTable.Key,
                                 count = groupedTable.Count()
                             });

より複雑なオーバーロードを使用GroupByして、1 回の呼び出しで実行することもできます。

var query = dataTable.AsEnumerable()
                     .GroupBy(x => table.Field<string>(Column1),
                              (key, group) => { value = key, 
                                                count = group.Count() },
                              StringComparer.InvariantCultureIgnoreCase));

明らかに、それはインバリアント カルチャを使用しています。現在のカルチャまたは順序規則を使用することもできます。

于 2009-09-29T07:19:01.883 に答える
3

This MSDN article has some information on datasets and case sensitivity..

You can control the case sensitivity of filtering, searching, and sorting by setting the dataset's CaseSensitive property.

于 2009-09-29T07:02:33.683 に答える
0
var query = dt.AsEnumerable()
              .GroupBy(r => r.Field<string>("Mes"))
              .Select(g => new { Mes = g.Key, 
                                 Tns = g.Sum(s => Convert.ToDecimal(s.Field<string>("Tns"))) })
              .OrderBy(g => g.Mes.First())
              .Where(g => g.Mes == ddlMes.SelectedValue.ToString());
于 2012-03-01T07:00:50.683 に答える