C# LINQ 中的 IN 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/959752/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:17:08  来源:igfitidea点击:

Where IN clause in LINQ

c#linq

提问by priyanka.sarkar

How to make a where in clause similar to one in SQL Server?

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

I made one by myself but can anyone please improve this?

我自己做了一个,但有人可以改进吗?

    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;
    }

采纳答案by Daniel Brückner

This expression should do what you want to achieve.

这个表达式应该做你想要实现的。

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))

回答by Scott Ivey

This will translate to a where in clause in Linq to SQL...

这将转换为 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));

In the case of your query, you could do something like this...

对于您的查询,您可以执行以下操作...

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});

回答by Andrija

from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state

回答by nikmd23

The "IN" clause is built into linq via the .Contains() method.

“IN”子句通过 .Contains() 方法内置到 linq 中。

For example, to get all People whose .States's are "NY" or "FL":

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

using (DataContext dc = new DataContext("connectionstring"))
{
    List<string> states = new List<string>(){"NY", "FL"};
    List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}

回答by Siva

public List<State> GetcountryCodeStates(List<string> countryCodes)
{
    List<State> states = new List<State>();
    states = (from a in _objdatasources.StateList.AsEnumerable()
    where countryCodes.Any(c => c.Contains(a.CountryCode))
    select a).ToList();
    return states;
}

回答by Laksh

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

这个有点不同的想法。但它会对你有用。我在 linq 主查询中使用了子查询。

Problem:

问题:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate)composite Keys : name,version

假设我们有文档表。架构如下架构:文档(名称,版本,授权,修改日期)复合键:名称,版本

So we need to get latest versions of all documents.

所以我们需要获取所有文档的最新版本。

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();

回答by nawfal

I like it as an extension method:

我喜欢它作为扩展方法:

public static bool In<T>(this T source, params T[] list)
{
    return list.Contains(source);
}

Now you call:

现在你打电话:

var states = _objdatasources.StateList().Where(s => s.In(countrycodes));

You can pass individual values too:

您也可以传递单个值:

var states = tooManyStates.Where(s => s.In("x", "y", "z"));

Feels more natural and closer to sql.

感觉更自然,更接近sql。

回答by Libertine

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>();
    }
}