如何提取Linq表达式的结果?

时间:2012-04-17 10:25:31

标签: c# linq c#-4.0

我的结果表达式是

 var result = dtFields.AsEnumerable().Join(dtCDGroup.AsEnumerable(),
                                fieldList=>fieldList.Field<string>("CDGroupID"),
                                cd=>cd.Field<string>("CDGroupID"),
                                (fieldList,cd) => new 
                                {
                                    FieldID = fieldList.Field<string>("FieldID"),
                                    Name = cd.Field<string>("Name"),
                                    CDCaption = fieldList.Field<string>("CDCaption"),
                                    Priority = ((cd.Field<string>("Priority") == null) ? 99 : cd.Field<int>("Priority")),
                                    fldIndex = fieldList.Field<string>("fldIndex")
                                }).OrderBy(result => result.Priority).ThenBy(result => result.fldIndex);

将上面的结果转换为数组或列表会抛出无效的强制转换异常。 如何提取上述表达式的结果?

2 个答案:

答案 0 :(得分:2)

分别添加.ToArray()或.ToList()调用

答案 1 :(得分:0)

尝试添加强类型:

public class NewModule
{
    public int FieldID { get; set; }
    public string Name { get; set; }
    public string CDCaption { get; set; }
    public int Priority { get; set; }
    public int fldIndex { get; set; }
}

而不是匿名类型,那么您可以像这样使用ToList<NewModule>()

var result = dtFields.AsEnumerable().Join(dtCDGroup.AsEnumerable(),
                            fieldList=>fieldList.Field<string>("CDGroupID"),
                            cd=>cd.Field<string>("CDGroupID"),
                            (fieldList,cd) => new NewModule
                            {
                                FieldID = fieldList.Field<string>("FieldID"),
                                Name = cd.Field<string>("Name"),
                                CDCaption = fieldList.Field<string>("CDCaption"),
                                Priority = ((cd.Field<string>("Priority") == null) ? 99 : cd.Field<int>("Priority")),
                                fldIndex = fieldList.Field<string>("fldIndex")
                            }).OrderBy(result => result.Priority)
                            .ThenBy(result => result.fldIndex)
                            .ToList<NewModule>();