C# LINQ使用Distinct方法检查对象某个属性的值是否重复
C# LINQ使用Distinct方法检查对象某个属性的值是否重复
扫一扫加微信
方案一:采用GroupBy方式, Count()>1为重复对象
C# Code:
List<tb_TablesDetail> list = gcStuct.DataSource as List<tb_TablesDetail>;
var query = list.GroupBy(x => x.FieldName.ToUpper())//区分大小写,转换为大写
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
if (query.Count>0)
{
var strFields = String.Join(",", query.ToArray());//连接重复的字段
Msg.Warning($"字段名<{strFields}>重复,请检查!");
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
var query = list.GroupBy(x => x.FieldName.ToUpper())//区分大小写,转换为大写
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
if (query.Count>0)
{
var strFields = String.Join(",", query.ToArray());//连接重复的字段
Msg.Warning($"字段名<{strFields}>重复,请检查!");
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
方案二:采用Distinct方式,然后比较对象数量是否一致
C# Code:
List<tb_TablesDetail> list = gcStuct.DataSource as List<tb_TablesDetail>;
var fields = list.Select(a => a.FieldName).Distinct();
if (fields.Count() != list.Count)
{
Msg.Warning("字段名称重复,请检查!");
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
var fields = list.Select(a => a.FieldName).Distinct();
if (fields.Count() != list.Count)
{
Msg.Warning("字段名称重复,请检查!");
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
方案三:采用Distinct方法,自定义比较对象的模型与算法
C# Code:
//LINQ使用Distinct方法检查对象某个属性的值是否重复
var q = list.Distinct(new DataCompareModel());
if (q.Count() < list.Count)
{
string msg = "{\"status\":0, \"msg\":\"字段名称有重复,请检查!\"}";
context.Response.Write(msg);
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
var q = list.Distinct(new DataCompareModel());
if (q.Count() < list.Count)
{
string msg = "{\"status\":0, \"msg\":\"字段名称有重复,请检查!\"}";
context.Response.Write(msg);
return;
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
C# Code:
/// <summary>
/// 对象比较
/// </summary>
public class DataCompareModel : IEqualityComparer<libs.ExcelDataModel>
{
public bool Equals(libs.ExcelDataModel x, libs.ExcelDataModel y)
{
return x.FieldName.CompareTo(y.FieldName) == 0;
}
public int GetHashCode(libs.ExcelDataModel obj)
{
return this.GetHashCode();
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
/// 对象比较
/// </summary>
public class DataCompareModel : IEqualityComparer<libs.ExcelDataModel>
{
public bool Equals(libs.ExcelDataModel x, libs.ExcelDataModel y)
{
return x.FieldName.CompareTo(y.FieldName) == 0;
}
public int GetHashCode(libs.ExcelDataModel obj)
{
return this.GetHashCode();
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
扫一扫加微信
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网