我有一个类ClientState
Class ClientState
{
Public int ID{get;set;}
public string State{get;set;}
}
List<ClientState> listClientState
包含USA的所有状态,现在问题可能是listClientState包含一些具有重复状态的对象。
如何过滤listClientState以删除重复记录
答案 0 :(得分:2)
你可以写一个比较器
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解决方案就会这样做。
答案 1 :(得分:1)
你试过listClientState.Distinct().ToList()
答案 2 :(得分:0)
您可以使用HashSet<>
,它不允许重复(它只是在Add()上忽略它们)。除了发布的答案,您还可以从列表中创建一个HashSet,并忽略所有重复项:
HashSet<ClientState> noDupes = new HashSet<ClientState>(listWithDupes);
List<ClientState> listNoDupes = noDupes.ToList();
答案 3 :(得分:0)
非常简单的例子:
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