有的时候我们需要对重复数据进行过滤,
针对数组可以用List.Distinct(),可以过滤掉重复的内容,
而针对对象中的某些字段只能用Distinct(IEqualityComparer<T>)
代码示例如下:
方法:
View Code
/// <summary>
/// 判断是否包含Oracle错误
/// </summary>
private bool HasOracleError(string input)
{
bool hasError = false;
//白名单
string[] ignoreList = Rondi.Commons.AppSettingConfig.Instance.IgnoreOracleCode;
Regex regex = new Regex(@"ORACLE 错误 (\d+)", RegexOptions.IgnoreCase);
List<string> lst = new List<string>();
MatchCollection matchs = regex.Matches(input);
foreach (Match match in matchs)
{
lst.Add(match.Groups[1].Value);
}
IEnumerable<string> ienumList = lst.Distinct(new ComparintString());//排重
IEnumerable<string> list = ienumList.SkipWhile(p => ignoreList.Contains(p));//过滤白名单
if (list.Count() > 0)
{
hasError = true;
}
return hasError;
}
接口实现:
View Code
/// <summary>
/// 字符串比较接口实现
/// </summary>
public class ComparintString : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (x == null && y == null) return false;
return x.Equals(y);
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}