Dan
Dan

Reputation: 1575

IN clause in Lambda expression against a List as reference

How to use IN clause having a list as reference?

List<PostOrcamentoServico> lOrcamentos = db.PostOrcamentoServico.Where(o => !o.Post.Usuarios.UsuEmail.Contains(User.Identity.Name) &&
                                                                       usuario.Clientes.Servicos.Contains(o.Servicos))
                                                                       .ToList();

in the above example, o.Servicos is a list.

Resuming: What I dould like to know how to do is use IN, however, using a list as reference:

myList.Contains(anotherList)

Upvotes: 0

Views: 1692

Answers (3)

Dan
Dan

Reputation: 1575

the right answer is this:

First: I get a list of items to compare:

var servicios = usuario.Clientes.Servicos.Select(s => s.SerId);

then I use this list with values to compare in my 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();

Upvotes: 0

Fabienne B.
Fabienne B.

Reputation: 363

From memory, you can do :

bool b = anotherList.All(x=> myList.Contains(x));

[EDIT] here a full test sample:

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

        }
    }
}

Upvotes: 2

sm_
sm_

Reputation: 2602

use this :

bool contained = !subset.Except(superset).Any();

reference :

Determine if a sequence contains all elements of another sequence using Linq

Upvotes: 0

Related Questions