我有一个类ClientState删除重复值
Class ClientState
{
Public int ID{get;set;}
public string State{get;set;}
}
List<ClientState> listClientState
包含,可能现在美国各州的问题是listClientState包含一些对象具有重复的状态。 如何过滤listClientState删除重复记录
我有一个类ClientState删除重复值
Class ClientState
{
Public int ID{get;set;}
public string State{get;set;}
}
List<ClientState> listClientState
包含,可能现在美国各州的问题是listClientState包含一些对象具有重复的状态。 如何过滤listClientState删除重复记录
你尝试listClientState.Distinct().ToList()
你可以写一个比较器
class ClientStatesComparer : IEqualityComparer<ClientState>
{
public bool Equals(ClientState x, ClientState y)
{
return x.State = y.State;
}
public int GetHashCode(ClientState obj)
{
return obj.State;
}
}
,并使用
listClientState = listClientState.Distinct(new ClientStatesComparer()).ToList();
你当然会松动记录(即松开身份证)这种方式。如果每个ID都是一个国家的唯一身份,Veers解决方案就可以做到。
你可以使用HashSet<>
,它不允许重复(它只是在Add()上忽略它们)。除了公布答案,你也可以创建一个列表HashSet的,和所有的副本都将被忽略:
HashSet<ClientState> noDupes = new HashSet<ClientState>(listWithDupes);
List<ClientState> listNoDupes = noDupes.ToList();
很简单的例子:
public class ClientState : IComparable<ClientState>
{
public int ID { get; set; }
public string State { get; set; }
public override string ToString()
{
return String.Format("ID: {0}, State: {1}", ID, State);
}
#region IComparable<ClientState> Members
public int CompareTo(ClientState other)
{
return other.State.CompareTo(State);
}
#endregion
}
static void Main(string[] args)
{
List<ClientState> clientStates = new List<ClientState>
{
new ClientState() {ID = 1, State = "state 1"},
new ClientState() {ID = 2, State = "state 1"},
new ClientState() {ID = 4, State = "state 3"},
new ClientState() {ID = 11, State = "state 2"},
new ClientState() {ID = 14, State = "state 1"},
new ClientState() {ID = 15, State = "state 2"},
new ClientState() {ID = 21, State = "state 1"},
new ClientState() {ID = 20, State = "state 2"},
new ClientState() {ID = 51, State = "state 1"}
};
removeDuplicates(clientStates);
Console.ReadLine();
}
private static void removeDuplicates(IList<ClientState> clientStatesWithPossibleDuplicates)
{
for (int i = 0; i < clientStatesWithPossibleDuplicates.Count; ++i)
{
for (int j = 0; j < clientStatesWithPossibleDuplicates.Count; ++j)
{
if (i != j)
{
if (clientStatesWithPossibleDuplicates[i].CompareTo(clientStatesWithPossibleDuplicates[j]) == 0)
{
clientStatesWithPossibleDuplicates.RemoveAt(i);
i = 0;
}
}
}
}
}
输出:
ID: 4, State: state 3
ID: 20, State: state 2
ID: 51, State: state 1
这是一个笑话吗? – 2010-04-30 10:47:16
是的,但它可以完成这项工作:P如果需要,您可以随时对其进行优化。 – 2010-04-30 10:49:51
你可以有两个具有不同ID但具有相同状态的ClientState吗?如果是这样,那么在复制品被删除后,您希望在列表中保留哪两个ID? – 2010-04-30 10:10:14