【问题标题】:How to put an Entity Framework query result into a List如何将实体框架查询结果放入列表
【发布时间】:2012-01-10 03:18:10
【问题描述】:

如何将以下查询结果放入列表中

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

【问题讨论】:

  • IEnumerable<T> 有一个 ToList 扩展方法。你试过吗?

标签: c# entity-framework c#-4.0


【解决方案1】:

最终编辑

根据您上次的评论,这就是您所需要的全部

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

当然与

相同
var result = sb.Swithches_SW_PanalComponents.ToList();

编辑

根据您的 cmets,我认为这就是您想要的:

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

结束编辑

ToList 方法是您想要的。但考虑使用点表示法。对于像这样的简单查询,它更干净、更简洁。

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

另外请注意,如果您只是想立即执行查询,并且只需要对其进行枚举,您也可以调用AsEnumerable()

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

这里的优点是结果是一个不太具体的类型——IEnumerablt&lt;T&gt;

【讨论】:

  • @desaivv - 除非我在进行连接,否则我几乎从不使用查询语法。
  • 我想把Var结果中存储的结果放到List变量中
  • @major - 如果你想要它作为List&lt;T&gt;,那么 ToList() 就可以了。我只是说针对最不具体的类型进行编码通常是个好主意——即 IEnumerable 而不是 List
  • 我想要的是能够编写以下代码'List MyList = new List();' '我的列表=结果; //使用某种方法将 result 转换为 List ' 我想这样做的原因是我想添加项目并从列表中删除项目和使用列表的 add() 和 remove() 方法。
  • @major - 好的,然后像 Icarus 和我的 ToList 会这样做
【解决方案2】:

像这样:

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

【讨论】:

  • 确保您的参考 System.Linq。
【解决方案3】:

我终于来了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多