Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ中的Where IN子句_C#_Linq - Fatal编程技术网

C# LINQ中的Where IN子句

C# LINQ中的Where IN子句,c#,linq,C#,Linq,如何使where in子句类似于SQL Server中的where in子句 我自己做了一个,但有人能改进一下吗 public List<State> Wherein(string listofcountrycodes) { string[] countrycode = null; countrycode = listofcountrycodes.Split(','); List<State> stateli

如何使where in子句类似于SQL Server中的where in子句

我自己做了一个,但有人能改进一下吗

    public List<State> Wherein(string listofcountrycodes)
    {
        string[] countrycode = null;
        countrycode = listofcountrycodes.Split(',');
        List<State> statelist = new List<State>();

        for (int i = 0; i < countrycode.Length; i++)
        {
            _states.AddRange(
                 from states in _objdatasources.StateList()
                 where states.CountryCode == countrycode[i].ToString()
                 select new State
                 {
                    StateName  = states.StateName                    

                 });
        }
        return _states;
    }
公共列表(国家代码的字符串列表)
{
字符串[]countrycode=null;
countrycode=listofcountrycodes.Split(',');
List statelist=新列表();
for(int i=0;i
这将转换为Linq to SQL中的where in子句

var myInClause = new string[] {"One", "Two", "Three"};

var results = from x in MyTable
              where myInClause.Contains(x.SomeColumn)
              select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));
在您的查询中,您可以这样做

var results = from states in _objectdatasource.StateList()
              where listofcountrycodes.Contains(states.CountryCode)
              select new State
              {
                  StateName = states.StateName
              };
// OR
var results = _objectdatasource.StateList()
                  .Where(s => listofcountrycodes.Contains(s.CountryCode))
                  .Select(s => new State { StateName = s.StateName});

此表达式应该实现您想要实现的目标

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
“IN”子句通过.Contains()方法内置到linq中

例如,要获取.States为“NY”或“FL”的所有人:

使用(DataContext dc=newdatacontext(“connectionstring”))
{
列表状态=新列表(){“NY”,“FL”};
List List=(从dc.GetTable()中的p开始,其中states.Contains(p.State)选择p.ToList();
}
公共列表GetCountryCodeState(列出countryCodes)
{
列表状态=新列表();
states=(来自_objdatasources.StateList.AsEnumerable()中的
其中CountryCode.Any(c=>c.Contains(a.CountryCode))
选择一个.ToList();
返回状态;
}

这个想法有点不同。但它对你有用。我已经使用子查询在linq主查询中进行了转换

问题:

假设我们有一个文档表。模式如下 架构:文档(名称、版本、作者、修改人) 组合键:名称、版本

所以我们需要得到所有文件的最新版本

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

我喜欢它作为一种扩展方法:

public static bool In<T>(this T source, params T[] list)
{
    return list.Contains(source);
}
您也可以传递单个值:

var states = tooManyStates.Where(s => s.In("x", "y", "z"));
感觉更自然,更接近sql。

公共列表查询日志()
public List<Requirement> listInquiryLogged()
{
    using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
    {
        var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
        var result = from Q in dt.Requirements
                     where inq.Contains(Q.ID)
                     orderby Q.Description
                     select Q;

        return result.ToList<Requirement>();
    }
}
{ 使用(DataClassesDataContext dt=new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionString[“应用程序服务”].ConnectionString)) { var inq=newint[]{168316841685168616871688168816891690169116921693}; var结果=来自dt要求中的Q 其中inq.包含(Q.ID) orderby Q.描述 选择Q; 返回result.ToList(); } }
欢迎继续,在这里,解释为什么要使用您的解决方案,而不仅仅是如何使用,是一种很好的做法。这将使你的答案更有价值,并有助于进一步的读者更好地理解你是如何做到这一点的。我还建议您看看我们的FAQ:。这将比较字符串值,但ids呢???@JitendraPancholi如果您创建一个列表,您可以检查ids。在.NET4中支持它。不确定早期版本。我应该在哪里编写此扩展method@Rohaan,在任何静态类(不是泛型的,也不是嵌套的)中,如果您要重用linq中的Where部分,那么编写扩展类只需要一段时间。对答案投了赞成票,但只是想让其他遇到这个问题的人直接选择扩展方法路线。@Jurg这是经常需要的,不是吗?我一直在用它。适用于Linq to对象,没有尝试过IQueryables。不,我的意思是,它经常使用。但是,在特定的项目中,如果您只需要在单个控制器(aka once)中执行此操作,则不需要扩展方法。这更多的是为刚接触c#/linq:)的人准备的,谢谢也帮助了我+1它的等价方法语法是什么?非常感谢你,已经奋斗了好几天,这是唯一有效的方法。这是一个简单而有效的解决方案。
public static bool In<T>(this T source, params T[] list)
{
    return list.Contains(source);
}
var states = _objdatasources.StateList().Where(s => s.In(countrycodes));
var states = tooManyStates.Where(s => s.In("x", "y", "z"));
public List<Requirement> listInquiryLogged()
{
    using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
    {
        var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
        var result = from Q in dt.Requirements
                     where inq.Contains(Q.ID)
                     orderby Q.Description
                     select Q;

        return result.ToList<Requirement>();
    }
}