如何使用字典中的LINQ语句删除所有重复项:
Dictionary<Type1, Type2>()
Type2包含字符串属性ID。我想删除所有具有相同ID的条目
答案 0 :(得分:2)
您可以将字典分组到您想要的特定字段,然后获得匹配(或全部)的第一个值:
Traceback (most recent call last):
File "C:\path\to\py\ssltest.py", line 4, in <module>
r = requests.get('https://localhost:8081/api', cert=r'C:\path\to\cert\mule.crt')
File "C:\Python34\lib\site-packages\requests\api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "C:\Python34\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Python34\lib\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL] PEM lib (_ssl.c:2536)
或者,如果您不在乎为结果创建新词典:
Dictionary<Type1, Type2> d = new Dictionary<Type1, Type2>();
var entriesToBeRemoved = d.GroupBy(x => x.Value.SomeId)
.SelectMany(x => x.Skip(1))
.ToList()
;
foreach (var kvp in entriesToBeRemoved)
{
d.Remove(kvp.Key);
}
答案 1 :(得分:1)
这应该完全按照您的要求运作:
var removables =
dict
.ToLookup(x => x.Value.ID, x => x.Key)
.SelectMany(x => x.Skip(1))
.ToArray();
foreach (var key in removables)
{
dict.Remove(key);
}