简体   繁体   English

如何将实体框架查询结果放入列表

[英]How to put an Entity Framework query result into a List

How to Put the following query result into a List 如何将以下查询结果放入列表

var  result = from c in sb.Swithches_SW_PanalComponents
                     select new { c.ID,c.SW_PanalComponents.ComponentsName,c.ComponentValue };

FINAL EDIT 最后编辑

Based on your last comment, this is all you ever needed 根据您的最新评论,这就是您所需要的

List<Swithches_SW_PanalComponents> result = 
                                  sb.Swithches_SW_PanalComponents.ToList();

which of course is identical to 哪个当然与

var result = sb.Swithches_SW_PanalComponents.ToList();

EDIT 编辑

Based on your comments, I think this is what you want: 根据您的评论,我认为这是您想要的:

List<SW_PanalComponents> result = sb.Swithches_SW_PanalComponents
                  .Select(c => new SW_PanalComponents { /* initialize your fields */ })
                  .ToList();

END EDIT 结束编辑

The ToList method is what you want. ToList方法就是您想要的。 But consider using dot notation. 但是请考虑使用点符号。 For simple queries like this, it's much cleaner and trimmer. 对于像这样的简单查询,它更简洁。

var result = sb.Swithches_SW_PanalComponents
                  .Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
                  .ToList();

Also note that, if you're just trying to execute your query immediately, and only need to enumerate over it, you can also call AsEnumerable() 还要注意,如果您只是想立即执行查询,而只需要枚举它,则还可以调用AsEnumerable()

var result = sb.Swithches_SW_PanalComponents
                  .Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
                  .AsEnumerable();

The advantage here is that result is a less specific type— IEnumerablt<T> . 这样做的好处是结果是一种不太具体的类型IEnumerablt<T>

Like this: 像这样:

var  result =(from c in sb.Swithches_SW_PanalComponents
                     select new 
                     { c.ID,
                       c.SW_PanalComponents.ComponentsName,
                       c.ComponentValue 
                     }).ToList();

That what i came with finally: 我最终想到的是:

  List<Swithches_SW_PanalComponents> MyList = new List<Swithches_SW_PanalComponents>();
        var Result = from all in sb.Swithches_SW_PanalComponents
                     select all
                     ;
        MyList.AddRange(Result.ToList<Swithches_SW_PanalComponents>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM