如何提取 Linq 表达式的结果

本文关键字:Linq 表达式 结果 提取 何提取 | 更新日期: 2023-09-27 18:31:18

我的结果表达式是

 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);

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

如何提取 Linq 表达式的结果

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

尝试添加强类型类型:

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>();