Linq中对应SQL中in关键字的方法

最近在做一个小项目的时候碰到一个问题,需要在Linq语句中写一个类似于SQL语句中in的功能

类似于这个语句:select * from table where id in (1,2,3)。

但是在Linq中 in 已经作为一个关键字使用了,当然不可能再完成上述的功能,上网查找之后,发现在MSDN社区中,有人给出了答案。

下面用一个例子讲解一下

首先要有一个实例类,存储所要检索的数据

public class IS
        {
            public int id { get; set; }
            public string title { get; set; }
        }

然后在Main方法中:

List<IS> ll = new List<IS>()
                                    {
                                        new IS{id=1, title="一" },
                                        new IS{id=2, title="二" },
                                        new IS{id=3, title="三" },
                                        new IS{id=4, title="四" },
                                        new IS{id=5, title="五" }
                                    };
            List<int> li = new List<int>() {1,2,3 };
            List<IS> ltem = (from g in ll where li.Contains(g.id) select g).ToList();
            foreach (var item in ltem)
            {
                 Console.WriteLine(string.Format("{0}",item.title));
            }
            Console.ReadLine();

关键一句在于:

from g in ll where li.Contains(g.id) select g

使用Contains方法来查询li中是否包含当前这条记录的信息

如果大家有什么更好的方法,请多多指教

posted @ 2009-04-17 10:52  小鲨  阅读(2050)  评论(0编辑  收藏  举报