如何在C#

时间:2018-10-30 09:15:39

标签: c# linq anonymous-types

我是C#和Linq的新手。

实际上,我想将匿名类型返回到列表中。匿名类型包含List,String和DateTime。我尝试使用下面的代码,但给出了错误。请帮助并告诉我我所缺少的内容或建议如何实现此目标。

//错误:

System.InvalidCastException: Specified cast is not valid..

//编辑的C#Linq代码

        public List<AuditInfo> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null,
            string user = null, Pager pager = null)
        {
            using (var ctx = new PlantDataContext())
            {
                var query = from audit in ctx.AuditLog
                            join ent in ctx.Scans on audit.RecordId equals ent.Id.ToString() into audits
                            from entaudits in audits.DefaultIfEmpty()
                            where audit.TypeFullName == "ABCD.DB.Model.Scan"
                            select new
                            {
                                audit,
                                entaudits
                            };

                if (Id != null)
                {
                    query = query.Where(x => x.audit.RecordId == Id.ToString());
                }
                if (fromTime.HasValue)
                {
                    var tmp = new DateTimeOffset(fromTime.Value.ToUniversalTime());
                    query = query.Where(x => x.audit.EventDateUTC >= tmp);
                }
                if (toTime.HasValue)
                {
                    var tmp = new DateTimeOffset(toTime.Value.ToUniversalTime());
                    query = query.Where(x => x.audit.EventDateUTC <= tmp);
                }
                if (!string.IsNullOrEmpty(type))
                {
                    var parseEvent = (EventType)Enum.Parse(typeof(EventType), type);
                    query = query.Where(x => x.audit.EventType == parseEvent);
                }
                if (!string.IsNullOrEmpty(user))
                {
                    query = query.Where(x => x.audit.UserName == user);
                }
                if (pager != null)
                {
                    var totalRecords = query.Count();
                    pager.TotalRecords = totalRecords;
                    var data = query.Select(x =>
                        new AuditInfo
                        {
                            x.audit.TypeFullName, //Here Error Occurs
                            x.audit.UserName,//Here Error Occurs
                            x.audit.EventType,//Here Error Occurs
                            x.audit.EventDateUTC,//Here Error Occurs
                            @LogDetails = x.audit.LogDetails.ToList(), //Here Error Occurs
                            x.entaudits.Name,
                            @Description = x.entaudits.Description
                        })
                        .OrderByDescending(x => x.EventDateUTC)
                        .Skip(pager.From)
                        .Take(pager.PageSize);
                    try
                    {
                        var list1 = data.ToList<AuditInfo>();
                    }
                    catch (Exception e)
                    {
                    }
                    var list = data.ToList<AuditInfo>();
                    pager.RecordCount = list.Count;
                    return list;
                }
                else
                {
                    var list = query.Select(x =>
                        new AuditInfo
                        {
                            x.audit.TypeFullName,
                            x.audit.UserName,
                            x.audit.EventType,
                            x.audit.EventDateUTC,
                            @LogDetails = x.audit.LogDetails.ToList(),
                            x.entaudits.Name,
                            @Description = x.entaudits.Description
                        })
                            .OrderByDescending(x => x.EventDateUTC)
                        .ToList<AuditInfo>();
                    return list;
                }
            }
        }

当我调试代码totalRecords变量时显示计数6,但是显示消息异常指定的强制转换在此行无效var list1 = data.ToList();

2 个答案:

答案 0 :(得分:2)

您必须将匿名对象转换为动态对象。

要使用linq执行此操作,可以使用Cast<dynamic> linq方法:

var list = query.Select(x =>
    new
    {
        x.audit.TypeFullName,
        x.audit.UserName,
        x.audit.EventType,
        x.audit.EventDateUTC,
        @LogDetails = x.audit.LogDetails.ToList(),
        x.entaudits.Name,
        @Description = x.entaudits.Description
    })
    .OrderByDescending(x => x.EventDateUTC)
    .AsEnumerable()
    .Cast<dynamic>()
    .ToList<dynamic>(); \\ here exception occures
return list;

答案 1 :(得分:2)

您可以为方法使用强返回类型,例如<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input type="text"> <input type="text">而不是List<ClassName>

List<dynamic>

那么您的查询将是

public List<ClassName> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null, string user = null, Pager pager = null)
{
   ...
}

您的强类型类看起来像

var data = query.Select(x =>
                new ClassName
                {
                    TypeFullName = x.audit.TypeFullName,
                    UserName = x.audit.UserName,
                    EventType = x.audit.EventType,
                    EventDateUTC = x.audit.EventDateUTC,
                    LogDetails = x.audit.LogDetails.ToList(),
                    Name = x.entaudits.Name,
                    Description = x.entaudits.Description
                })
                .OrderByDescending(x => x.EventDateUTC)
                .Skip(pager.From)
                .Take(pager.PageSize);

var list = data.ToList<ClassName>();

确保每个属性的数据类型在查询的public class ClassName { public string TypeFullName { get; set; } public string UserName { get; set; } public string EventType { get; set; } public DateTime EventDateUTC { get; set; } public List<LogDetail> LogDetails { get; set; } public string Name { get; set; } public string Description { get; set; } } 子句中都应匹配

编辑:

.Select