多列不区分大小写的组
反正有没有做LINQ2SQL查询做类似的事情:
var result = source.GroupBy(a => new { a.Column1, a.Column2 });
要么
var result = from s in source group s by new { s.Column1, s.Column2 } into c select new { Column1 = c.Key.Column1, Column2 = c.Key.Column2 };
但忽略了分组列内容的情况?
您可以将StringComparer.InvariantCultureIgnoreCase
传递给GroupBy
扩展方法。
var result = source.GroupBy(a => new { a.Column1, a.Column2 }, StringComparer.InvariantCultureIgnoreCase);
或者您可以根据Hamlet Hakobyan的建议在每个字段上使用ToUpperInvariant
进行评论。 我建议使用ToUpperInvariant
或ToUpper
而不是ToLower
或ToLowerInvariant
因为它针对编程比较目的进行了优化。
我无法让NaveenBhat的解决方案工作,收到编译错误:
无法从用法推断出方法’System.Linq.Enumerable.GroupBy(System.Collections.Generic.IEnumerable,System.Func,System.Collections.Generic.IEqualityComparer)’的类型参数。 尝试显式指定类型参数。
为了使它工作,我发现最容易和最清楚的是定义一个新类来存储我的键列(GroupKey),然后是一个实现IEqualityComparer(KeyComparer)的单独类。 然后我可以打电话
var result= source.GroupBy(r => new GroupKey(r), new KeyComparer());
KeyComparer类确实将字符串与InvariantCultureIgnoreCase比较器进行比较,因此对NaveenBhat表示赞赏,因为它指向了正确的方向。
我的课程的简化版本:
private class GroupKey { public string Column1{ get; set; } public string Column2{ get; set; } public GroupKey(SourceObject r) { this.Column1 = r.Column1; this.Column2 = r.Column2; } } private class KeyComparer: IEqualityComparer { bool IEqualityComparer .Equals(GroupKey x, GroupKey y) { if (!x.Column1.Equals(y.Column1,StringComparer.InvariantCultureIgnoreCase) return false; if (!x.Column2.Equals(y.Column2,StringComparer.InvariantCultureIgnoreCase) return false; return true; //my actual code is more complex than this, more columns to compare //and handles null strings, but you get the idea. } int IEqualityComparer .GetHashCode(GroupKey obj) { return 0.GetHashCode() ; // forces calling Equals //Note, it would be more efficient to do something like //string hcode = Column1.ToLower() + Column2.ToLower(); //return hcode.GetHashCode(); //but my object is more complex than this simplified example } }
我通过Table中的DataRow对象的值进行了相同的问题分组,但我只是在DataRow对象上使用.ToString()来解决编译器问题,例如
MyTable.AsEnumerable().GroupBy( dataRow => dataRow["Value"].ToString(), StringComparer.InvariantCultureIgnoreCase)
代替
上述就是C#学习教程:多列不区分大小写的组分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
MyTable.AsEnumerable().GroupBy( dataRow => dataRow["Value"], StringComparer.InvariantCultureIgnoreCase)
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/983567.html