Reputation: 901
Well I am trying to build a dictionary using linq to SQL. Not sure how to pick distinct values using the below query. The idea to is fetch the instances of a title between a date.
GolfitoDataContext db = new GolfitoDataContext();
var dic = db.GetTable<History>()
.Select(p => new { p.Title, p.Date }).Where(x => x.Date >= startDateFilter && x.Date <= endDateFilter)
.AsEnumerable()
.ToDictionary(k => k.Title, v => v.Date);
I get an exception that "An item with the same key has already been added."
I know its got to do with the "title" being repeated. But not sure how to apply the Distinct() method in the above condition to be able to build the dictionary. If I am doing something wrong, please correct me. Thanks!
Upvotes: 0
Views: 100
Reputation: 32729
You can do this by using MoreLinQ
var dic = db.GetTable<History>()
.Select(p => new { p.Title, p.Date }).Where(x => x.Date >= startDateFilter && x.Date <= endDateFilter)
.DistinctBy(x=>x.Title)
.AsEnumerable()
.ToDictionary(k => k.Title, v => v.Date);
Upvotes: 1
Reputation: 8669
This should work:
GolfitoDataContext db = new GolfitoDataContext();
var dic = db.GetTable<History>()
.Select(p => new { p.Title, p.Date }).Where(x => x.Date >= startDateFilter && x.Date <= endDateFilter)
.DistinctBy(p => p.Title)
.AsEnumerable()
.ToDictionary(k => k.Title, v => v.Date);
Upvotes: 3