需要将一堆来自可能具有重复键的对象的键/值对添加到字典中。只有第一个不同的键的实例(和实例的值)应该被添加到字典中。如何添加到字典时,可能有重复的键?
下面是一个示例实现,首先显示工作正常。
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。
看看LINQ ToLookup()方法 – sll
字典有ContainsKey函数。也许你可以在添加keyvaluepair – atbebtg