C# Linq to SQL 选择多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19106058/
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
Linq to SQL select multiple columns
提问by Benny Ae
I just want to select 2 columns from a MSSQL DB using LINQ.
我只想使用 LINQ 从 MSSQL DB 中选择 2 列。
The SQL should be
SQL应该是
select table.col1,table.col2 from table
I tried
我试过
IList<string> myResults =
(
from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
).Take(20).ToList();
but this didn't work.
但这没有用。
It says
它说
cannot convert type list <AnonymousType#1> to Ilist<string>
回答by Tobias
You are basically trying to fill a list of strings with the entries of a list of anonymous types, that won't work.
您基本上是在尝试用匿名类型列表的条目填充字符串列表,这是行不通的。
Have you tried something like this?:
你有没有尝试过这样的事情?:
var list = from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
Then you can easily use the entries in a loop for example
然后您可以轻松地使用循环中的条目,例如
foreach(var element in list) {
//...
}
Or like a list
或者像一个列表
list.Take(20).ToList();
回答by Ahsan
First of all, a list of strings (List<string>
) can only have one single string in an element not two (what you are trying to do here) changing the type to var would fix your exception but not sure if that is the solution you want.
首先,字符串列表 ( List<string>
) 在一个元素中只能有一个字符串,而不是两个(您在此处尝试执行的操作)将类型更改为 var 将修复您的异常,但不确定这是否是您想要的解决方案。
var myResults =
(
from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
).Take(20).ToList();
回答by AR M
You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.
您可以使用 linq Select 选择多个字段,如上面的各种示例所示,这将作为匿名类型返回。如果你想避免这种匿名类型,这里有一个简单的技巧。
var items = myResults.Select(f => new [] { f.Col1, f.Col2 }).SelectMany(item => item).Distinct();
I think this solves the problem
我认为这解决了问题