C# 如何将实体框架查询结果放入列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8798143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put an Entity Framework query result into a List
提问by major
How to Put the following query result into a List
如何将以下查询结果放入List
var result = from c in sb.Swithches_SW_PanalComponents
select new { c.ID,c.SW_PanalComponents.ComponentsName,c.ComponentValue };
采纳答案by Adam Rackis
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 ToListmethod is what you want. But consider using dot notation. For simple queries like this, it's much cleaner and trimmer.
该ToList方法是你想要的。但请考虑使用点表示法。对于像这样的简单查询,它更简洁、更简洁。
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>.
这里的优点是 result 是一个不太具体的类型 - IEnumerablt<T>。
回答by Icarus
Like this:
像这样:
var result =(from c in sb.Swithches_SW_PanalComponents
select new
{ c.ID,
c.SW_PanalComponents.ComponentsName,
c.ComponentValue
}).ToList();
回答by major
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>());

