我想将 EF 对象列表转换为字典。我在某种程度上完成了这一任务,但有一个缺点:我无法弄清楚如何根据该对象的属性将多个对象添加到一个键,值对。
例如,假设我有一个实体框架对象 TblValue
,它具有三个值 - ValueID、ValueNm、CodeID
。
CodeID
将在对象之间共享 - 有些可能相同,有些可能不同。
我想创建一个 Dictionary>
。 (TblCode
来自 CodeID
。)基本上,我想创建一个此项目列表的字典,其中每个列表都是分开的使用 LINQ 按 CodeID
分组。
我之前使用的 LINQ 语句可以工作,但它不会执行任何分组。这是非常接近的,还是 LINQ 不适合这个? foreach
循环会更好吗?
var splitTimes = times.Cast().ToDictionary(o => tr.GetCode(o.CodeID));
澄清 - 我无法对值....我无法创建 Dictionary>
,我只能创建一个字典
I'd like to convert a list of EF objects to a dictionary. I somewhat accomplished this, with one drawback: I can't figure out how to add multiple of the objects to one key,value
pair based on an attribute of that object.
For example say I have an Entity Framework object TblValue
with three values - ValueID, ValueNm, CodeID
.
The CodeID
will be shared among the objects - some may be the same and some may be different.
I would like to create a Dictionary<TblCode, List<TblData>>
. (TblCode
comes from CodeID
.) Basically, I want to create a dictionary of this list of items where each list is separated & grouped by the CodeID
, using LINQ.
The LINQ statement I was using before was working, but it wouldn't do any grouping. Is this pretty close, or is LINQ not appropriate for this? Would a foreach
loop be better?
var splitTimes = times.Cast<TblValue>().ToDictionary(o => tr.GetCode(o.CodeID));
clarification - I am unable to group the values....I cannot create a Dictionary<TblCode, List<TblValue>>
, I can only create a Dictionary<TblCode, TblValue>
发布评论
评论(2)
您需要先分组,然后转换为字典。就像这样:
如果您需要转换密钥,请在
GroupBy()
或ToDictionary()
中进行转换You need to first group and then convert to dictionary. Like that:
If you need to convert you key do it in either
GroupBy()
orToDictionary()
我找到了一种方法来做到这一点,the_joric 的答案很接近,但我必须在值上显式调用
ToList()
。var splitTimes = times.GroupBy(x => x.ProjCdId).ToDictionary(o => tr.GetProjCd(o.Key), o => o.ToList());
I found a way to do it, the_joric's answer was close but I had to explicitly call
ToList()
on the values.var splitTimes = times.GroupBy(x => x.ProjCdId).ToDictionary(o => tr.GetProjCd(o.Key), o => o.ToList());