Lambda 表达式中的 IN 子句针对列表作为参考
IN clause in Lambda expression against a List as reference
如何使用以列表为参考的IN子句?
List<PostOrcamentoServico> lOrcamentos = db.PostOrcamentoServico.Where(o => !o.Post.Usuarios.UsuEmail.Contains(User.Identity.Name) &&
usuario.Clientes.Servicos.Contains(o.Servicos))
.ToList();
在上面的例子中,o.Servicos是一个列表。
恢复:我想知道如何使用 IN,但是,使用列表作为参考:
myList.Contains(anotherList)
使用这个:
bool contained = !subset.Except(superset).Any();
参考:
Determine if a sequence contains all elements of another sequence using Linq
根据记忆,你可以这样做:
bool b = anotherList.All(x=> myList.Contains(x));
[编辑] 这里是一个完整的测试样本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
List<string> l1 = new List<string>();
l1.Add("toto");l1.Add("titi") ;l1. Add("tata") ;l1.Add("tutu") ;l1.Add("tete");
List<string> l2 = new List<string>();
l2.Add("toto"); l2.Add ("titi"); l2.Add ( "tata") ;
if (l2.All(l1.Contains))
{
System.Console.WriteLine("OK");
}
else
{
System.Console.WriteLine("KO");
}
}
}
}
正确答案是:
首先:我得到要比较的项目列表:
var servicios = usuario.Clientes.Servicos.Select(s => s.SerId);
然后我使用这个列表和值在我的 IN 中进行比较:
List<PostOrcamentoServico> lOrcamentos = db.PostOrcamentoServico.Where(os => !os.Post.Usuarios.UsuEmail.Contains(User.Identity.Name)&&
os.Servicos.All(s => servicios.Contains(s.SerId))).ToList();
如何使用以列表为参考的IN子句?
List<PostOrcamentoServico> lOrcamentos = db.PostOrcamentoServico.Where(o => !o.Post.Usuarios.UsuEmail.Contains(User.Identity.Name) &&
usuario.Clientes.Servicos.Contains(o.Servicos))
.ToList();
在上面的例子中,o.Servicos是一个列表。
恢复:我想知道如何使用 IN,但是,使用列表作为参考:
myList.Contains(anotherList)
使用这个:
bool contained = !subset.Except(superset).Any();
参考:
Determine if a sequence contains all elements of another sequence using Linq
根据记忆,你可以这样做:
bool b = anotherList.All(x=> myList.Contains(x));
[编辑] 这里是一个完整的测试样本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
List<string> l1 = new List<string>();
l1.Add("toto");l1.Add("titi") ;l1. Add("tata") ;l1.Add("tutu") ;l1.Add("tete");
List<string> l2 = new List<string>();
l2.Add("toto"); l2.Add ("titi"); l2.Add ( "tata") ;
if (l2.All(l1.Contains))
{
System.Console.WriteLine("OK");
}
else
{
System.Console.WriteLine("KO");
}
}
}
}
正确答案是:
首先:我得到要比较的项目列表:
var servicios = usuario.Clientes.Servicos.Select(s => s.SerId);
然后我使用这个列表和值在我的 IN 中进行比较:
List<PostOrcamentoServico> lOrcamentos = db.PostOrcamentoServico.Where(os => !os.Post.Usuarios.UsuEmail.Contains(User.Identity.Name)&&
os.Servicos.All(s => servicios.Contains(s.SerId))).ToList();