关于LINQ中IN的疑问
在LINQ中需要实现SQL中类似IN的功能,于是使用下面的方法,发现其无法正常工作
public void GetData(IList<long> lst) {
MyConnection conn = new MyConnection (this.ConnectString);
MyDataContext db = new MyDataContext (conn);
var res=from al in db.MyTable
where lst.Contains(al.ID)
select al;
// do something
}
经过试验,将IList转换为数组后可以正常工作
public void GetData(IList<long> lst) {
MyConnection conn = new MyConnection (this.ConnectString);
MyDataContext db = new MyDataContext (conn);
long[] ins =lst.ToArray();
var res=from al in db.MyTable
where ins.Contains(al.ID)
select al;
// do something
}
大家有没有遇到类似的问题,这是什么原因呢?
[解决办法]
Linq不支持IList的Contains方法,但支持数组的。
[解决办法]
应该是可以的哦
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace 图片翻页
{
public partial class WebForm1 : System.Web.UI.Page
{
public class mytable
{
public int ID { get; set; }
public string name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<mytable> list = new List<mytable>() { new mytable() { ID = 10, name = "ID1" }, new mytable() { ID = 20, name = "ID2" }, new mytable() { ID = 40, name = "ID4" }, new mytable() { ID = 30, name = "ID3" } };
IList<long> lst = new List<long>() { 10, 20,40 };
var res = from al in list
where lst.Contains(al.ID)
select al;
res.ToList().ForEach(x => Response.Write(x.name));
}
}
}
}
[解决办法]
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Array : ICloneable,
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
数组也是继承自 IList的,所以不应该存在你的问题
[解决办法]
楼主 用的是 linq to sql ?
linq to sql 的集查询方法好像是要有实现的,既具体的方法。
如:Contains 方法如果是 接口本身的Contains只是一个未实现方法声明 故无法转换。
如果是 使用具体的类的Contains,如 List Array 等都是可以的,
或者是使用 linq 的扩展方法Contains 也是可以转换的,但是注意 扩展方法的优先级低于类/接口本身的同名方法。
EF 应该没有此问题
[解决办法]
应该是这样。
public void GetData(IList<long> lst) {
MyConnection conn = new MyConnection (this.ConnectString);
MyDataContext db = new MyDataContext (conn);
var res=from al in db.MyTable
where lst.ToArray().Contains(al.ID)
select al;
// do something
}
也不费你多少事。
这不说明什么,因为IList不是“继承”数组,所以数组可以不代表IList可以。好比人会说话,不代表哺乳动物会说话。
[解决办法]
LINQ to SQL和你写的情况有些不同。
看了部分stackoverflow上的贴子
http://stackoverflow.com/questions/961912/stack-overflow-in-linq-to-sql-and-the-contains-keyword
http://stackoverflow.com/questions/7066883/linq-to-sql-method-with-contains-fails
LINQ to SQL的Contains似乎不支持接口IList,但支持List。可能是个bug……
[解决办法]
又看到篇相关的文章,可以用IEnumerable代替IList接口:
http://johnliu.net/blog/2008/4/9/the-funkiness-that-is-linqcontains.html