Linq to Dictionary<string, List<string>> with Null values
Why would you expect that in the first place? You're literally telling it to just select value
. Neither cultureId
nor your Languages
array are even mentioned or utilized, so why would you even expect them to somehow play a part?
You'd need something like the following GroupBy
:
.GroupBy(g => g.key, (key, items) => Languages.Select(lang => items.FirstOrDefault(i => i.cultureId == lang)?.value))
You can do some join with your languages list, something like this (untested yet)
Dictionary<string, List<string>> query = Translation
.GroupBy(o => o.key)
.ToDictionary(g => g.Key, g =>
Languages.Select(l => g.FirstOrDefault(x => x.cultureId == l)?.value));
Explanation :
We map the group on the list of languages. For each langage, if a matching element with cultureId is in the group, use that value, or instead use null.
(can't test right now, pardon me in advance for any error)
You try to do a "left join" in linq, that is possible using Join
and DefaultIfEmpty
operators.
As long as I know this only can be made on a declarative syntax:
var query = from trans in Translation
group trans by trans.key into transGroup
select new
{
transGroup.Key,
Values = from langId in Languages
join trans in transGroup on langId equals trans.cultureId
into joint
from trans in joint.DefaultIfEmpty()
select trans?.value
};
var values = query.ToDictionary(x => x.Key, x => x.Values.ToList());
I agree it's not the most readable query and maybe it would be simpler to maintain doing it on a procedural way.