需要将来自可能具有重复键的对象的一堆键/值对添加到字典中。仅将键的第一个不同实例(及其实例的值)添加到字典中。
下面是一个示例实现,起初看起来效果很好。
void Main()
{
Dictionary<long, DateTime> items = new Dictionary<long, DateTime>();
items = AllItems.Select(item =>
{
long value;
bool parseSuccess = long.TryParse(item.Key, out value);
return new { value = value, parseSuccess, item.Value };
})
.Where(parsed => parsed.parseSuccess && !items.ContainsKey(parsed.value))
.Select(parsed => new { parsed.value, parsed.Value })
.Distinct()
.ToDictionary(e => e.value, e => e.Value);
Console.WriteLine(string.Format("Distinct: {0}{1}Non-distinct: {2}",items.Count, Environment.NewLine, AllItems.Count));
}
public List<KeyValuePair<string, DateTime>> AllItems
{
get
{
List<KeyValuePair<string, DateTime>> toReturn = new List<KeyValuePair<string, DateTime>>();
for (int i = 1000; i < 1100; i++)
{
toReturn.Add(new KeyValuePair<string, DateTime>(i.ToString(), DateTime.Now));
toReturn.Add(new KeyValuePair<string, DateTime>(i.ToString(), DateTime.Now));
}
return toReturn;
}
}
但是,如果将AllItems修改为返回更多对,则会发生ArgumentException:“已经添加了具有相同键的项。”
void Main()
{
Dictionary<long, DateTime> items = new Dictionary<long, DateTime>();
var AllItems = PartOne.Union(PartTwo);
Console.WriteLine("Total items: " + AllItems.Count());
items = AllItems.Select(item =>
{
long value;
bool parseSuccess = long.TryParse(item.Key, out value);
return new { value = value, parseSuccess, item.Value };
})
.Where(parsed => parsed.parseSuccess && !items.ContainsKey(parsed.value))
.Select(parsed => new { parsed.value, parsed.Value })
.Distinct()
.ToDictionary(e => e.value, e => e.Value);
Console.WriteLine("Distinct: {0}{1}Non-distinct: {2}",items.Count, Environment.NewLine, AllItems.Count());
}
public IEnumerable<KeyValuePair<string, DateTime>> PartOne
{
get
{
for (int i = 10000000; i < 11000000; i++)
{
yield return (new KeyValuePair<string, DateTime>(i.ToString(), DateTime.Now));
}
}
}
public IEnumerable<KeyValuePair<string, DateTime>> PartTwo
{
get
{
for (int i = 10000000; i < 11000000; i++)
{
yield return (new KeyValuePair<string, DateTime>(i.ToString(), DateTime.Now));
}
}
}
做到这一点的最佳方法是什么?请注意,解决方案中需要使用
long.TryParse
,因为实际输入可能不包括有效的Int64。
最佳答案
仅键的第一个不同的实例(以及实例的值)
应该添加到字典中。
您可以使用Enumerable.GroupBy
方法并采用组中的第一个值来实现此目的:
items = AllItems.Select(item =>
{
long value;
bool parseSuccess = long.TryParse(item.Key, out value);
return new { Key = value, parseSuccess, item.Value };
})
.Where(parsed => parsed.parseSuccess)
.GroupBy(o => o.Key)
.ToDictionary(e => e.Key, e => e.First().Value)
关于c# - 可能有重复的键时如何添加到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7676711/