sch*_*ack 1 c# linq dictionary
需要将来自可能具有重复键的对象的一组键/值对添加到字典中.只应将键的第一个不同实例(以及实例的值)添加到字典中.
下面是一个示例实现,首先出现,以便正常工作.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果修改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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
完成此任务的最佳方法是什么?请注意,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)
Run Code Online (Sandbox Code Playgroud)