首页 / C# / c# – 从字符串数组中删除重复项
c# – 从字符串数组中删除重复项
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 从字符串数组中删除重复项,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2355字,纯文字阅读大概需要4分钟。
内容图文
我是C#的新手,看过很多帖子,但我仍然很困惑.
我有一个数组列表:
List<Array> moves = new List<Array>();
我正在使用以下内容添加移动:
string[] newmove = { piece, axis.ToString(), direction.ToString() };
moves.Add(newmove);
现在我希望使用以下内容删除重复项:
moves = moves.Distinct();
然而,这不是让我这样做的.我收到此错误:
无法将类型’System.Collections.Generic.IEnumerable’隐式转换为’System.Collections.Generic.List’.存在显式转换(您是否错过了演员?)
请帮忙?我会非常感激的.
史蒂夫
解决方法:
您的代码有两个错误.第一个是对ToList的缺失调用,正如已经指出的那样.第二是微妙的. Unique按标识比较对象,但重复的列表项具有不同的数组实例.
该问题有多种解决方案.
>在moves.Distinct().ToList()中使用自定义相等比较器.无需进一步更改.
示例实施:
class ArrayEqualityComparer<T> : EqualityComparer<T> {
public override bool Equals(T[] x, T[] y) {
if ( x == null ) return y == null;
else if ( y == null ) return false;
return x.SequenceEquals(y);
}
public override int GetHashCode(T[] obj) {
if ( obj == null) return 0;
return obj.Aggregate(0, (hash, x) => hash ^ x.GetHashCode());
}
}
过滤独特的项目:
moves = moves.Distinct(new ArrayEqualityComparer<string>()).ToList();
>使用元组< string,string,string>而不是字符串[].元组提供内置的结构平等和比较.由于长类型名称,此变体可能会使代码混乱.
实例:
List<Tuple<string, string, string>> moves =
new List<Tuple<string, string, string>>();
添加新动作:
Tuple<string, string, string> newmove =
Tuple.Create(piece, axis.ToString(), direction.ToString());
moves.Add(newmove);
过滤独特的项目:
moves = moves.Distinct().ToList();
>使用自定义类来保存三个值.我实际上推荐这个变种,因为它使你处理动作的所有代码更具可读性.
示例实施:
class Move {
public Move(string piece, string axis, string direction) {
Piece = piece;
Axis = axis;
Direction = direction;
}
string Piece { get; private set; }
string Axis { get; private set; }
string Direction { get; private set; }
public override Equals(object obj) {
Move other = obj as Move;
if ( other != null )
return Piece == other.Piece &&
Axis == other.Axis &&
Direction == other.Direction;
return false;
}
public override GetHashCode() {
return Piece.GetHashCode() ^
Axis.GetHashCode() ^
Direction.GetHashCode();
}
// TODO: override ToString() as well
}
实例:
List<Move> moves = new List<Move>();
添加新动作:
Move newmove = new Move(piece, axis.ToString(), direction.ToString());
moves.Add(newmove);
过滤独特的项目:
moves = moves.Distinct().ToList();
内容总结
以上是互联网集市为您收集整理的c# – 从字符串数组中删除重复项全部内容,希望文章能够帮你解决c# – 从字符串数组中删除重复项所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。