Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
SolvedPrivate

Anyway to have 2 "contains" in this LINQ?

Posted on 2014-11-24
22
Medium Priority
?
68 Views
Last Modified: 2016-02-15
This line of code gets all the users with RoleId of 1.

I want to get all the users with all the roles (RoleId =1, RoleId =2,etc)

Anyway to do this with LINQ?

 
var users = _dataContext.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains("1")).ToList();

Open in new window

0
Comment
Question by:Camillia
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 7
  • 2
  • +2
22 Comments
 
LVL 12

Expert Comment

by:FarWest
ID: 40462248
use this sample
List<string> cities = new List<string>() {"London", "Vancouver", "San Francisco"};

var cutomers = from c in Customers
        where cities.Contains(c.City)
        select c;

from
https://social.msdn.microsoft.com/Forums/en-US/47acd270-b097-4d5e-bfd1-4be25f7a0713/how-to-use-in-clause-in-linq?forum=linqtosql
0
 
LVL 34

Accepted Solution

by:
it_saige earned 1000 total points
ID: 40462292
Perhaps something like:
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28568474
{
	class Data
	{
		public string RoleID { get; set; }
	}

	class Program
	{
		readonly static List<Data> @set = new List<Data>()
		{ 
			new Data() { RoleID = "Role1"},
			new Data() { RoleID = "Role2"}
		};

		static void Main(string[] args)
		{
			var methodbased = @set.Where(x => x.RoleID.Contains("1") || x.RoleID.Contains("2")).Select(x => x.RoleID);
			var expressionbased = (from data in @set where data.RoleID.Contains("1") || data.RoleID.Contains("2") select data.RoleID);

			Console.WriteLine("Method based...");
			foreach (var item in methodbased)
				Console.WriteLine(item);

			Console.WriteLine("Expression based...");
			foreach (var item in expressionbased)
				Console.WriteLine(item);
			Console.ReadLine();
		}
	}
}

Open in new window


Produces the following output:Capture.JPG
-saige-
0
 
LVL 7

Author Comment

by:Camillia
ID: 40462329
Ah, I have to actually name the roles. For example, if someone down the road adds another role, I have to change the code.

There's no such thing as "get ALL the roles" without naming them, looks like it.
0
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

 
LVL 18

Expert Comment

by:Richard Lee
ID: 40462377
Hi Camilla,

You should check out the AccountController methods where you should find a lot of methods that suit your needs.

context.Roles.Select(r => r.Name)

Open in new window

0
 
LVL 34

Expert Comment

by:it_saige
ID: 40462386
Not really name (so to speak) but if you are wanting to get multiple integer values you either convert the integer to a string and then use String.Contains or select the values where the value matches a comparer, e.g. -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28568474
{
	class Data
	{
		public int RoleID { get; set; }
		public string Name { get; set; }
	}

	class Program
	{
		readonly static List<Data> @set = new List<Data>()
		{ 
			new Data() { RoleID = 1, Name = "Role1"},
			new Data() { RoleID = 2, Name = "Role2"},
			new Data() { RoleID = 3, Name = "Role3"},
			new Data() { RoleID = 31, Name = "Role31"},
		};

		static void Main(string[] args)
		{
			var MethodBaseIntEquals = @set.Where(x => x.RoleID.Equals(1) || x.RoleID.Equals(2)).Select(x => x.RoleID);
			var ExpressionBasedIntEquals = (from data in @set where data.RoleID.Equals(1) || data.RoleID.Equals(2) select data.RoleID);
			var MethodBaseStringContains = @set.Where(x => x.RoleID.ToString().Contains("1") || x.RoleID.ToString().Contains("2")).Select(x => x.RoleID);
			var ExpressionBasedStringContains = (from data in @set where data.RoleID.ToString().Contains("1") || data.RoleID.ToString().Contains("2") select data.RoleID);

			Console.WriteLine("Method based int equals...");
			foreach (var item in MethodBaseIntEquals)
				Console.WriteLine(item);

			Console.WriteLine();
			Console.WriteLine("Expression based int equals...");
			foreach (var item in ExpressionBasedIntEquals)
				Console.WriteLine(item);

			Console.WriteLine();
			Console.WriteLine("Method based string contains...");
			foreach (var item in MethodBaseStringContains)
				Console.WriteLine(item);

			Console.WriteLine();
			Console.WriteLine("Expression based string contains...");
			foreach (var item in ExpressionBasedStringContains)
				Console.WriteLine(item);
			Console.ReadLine();
		}
	}
}

Open in new window


Produces the following output:Capture.JPG
As to why your initial solution is not working, it is because you are using Enumerable.Contains, which is used to tell if an Enumerable contains a value and not used to select a value as part of a linq statement.

-saige-
0
 
LVL 7

Author Comment

by:Camillia
ID: 40462434
Thanks, i'll take a look
0
 
LVL 11

Assisted Solution

by:louisfr
louisfr earned 1000 total points
ID: 40463945
If the list of Roles is in _dataContext.Roles, you can use
var users = _dataContext.Users.Where(x => ! _dataContext.Roles.Select(y => y.RoleId).Except(x.Roles.Select(y => y.RoleId)).Any()).ToList()

Open in new window

0
 
LVL 7

Author Comment

by:Camillia
ID: 40464267
I'll try it, thanks
0
 
LVL 7

Author Comment

by:Camillia
ID: 40464749
I turned on Profiler and that LINQ comes out as this and doesn't bring back any rows --> louisfr

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Email] AS [Email], 
    [Extent1].[EmailConfirmed] AS [EmailConfirmed], 
    [Extent1].[PasswordHash] AS [PasswordHash], 
    [Extent1].[SecurityStamp] AS [SecurityStamp], 
    [Extent1].[PhoneNumber] AS [PhoneNumber], 
    [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed], 
    [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled], 
    [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc], 
    [Extent1].[LockoutEnabled] AS [LockoutEnabled], 
    [Extent1].[AccessFailedCount] AS [AccessFailedCount], 
    [Extent1].[UserName] AS [UserName]
    FROM [dbo].[AspNetUsers] AS [Extent1]
    WHERE  NOT EXISTS (SELECT 
        1 AS [C1]
        FROM  (SELECT 
            [Extent2].[Id] AS [Id]
            FROM [dbo].[AspNetRoles] AS [Extent2]
        EXCEPT
            SELECT 
            [Extent3].[RoleId] AS [RoleId]
            FROM [dbo].[AspNetUserRoles] AS [Extent3]
            WHERE [Extent1].[Id] = [Extent3].[UserId]) AS [Except1]
    )

Open in new window

0
 
LVL 11

Expert Comment

by:louisfr
ID: 40464916
If it brings no rows, maybe it means there are no users with all the roles.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40464928
I have one user with one role.
One user with no role.

It's ok if we can't figure it out. I can do it in a stored proc.
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40466258
How many roles is there?
0
 
LVL 7

Author Comment

by:Camillia
ID: 40466711
2 roles. But users belong to one role. They can't be in 2 roles.
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40469288
I quote: "I want to get all the users with all the roles"
If no user can have all the roles, then you won't get any user with all the roles.
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40469289
Do you want to get the users grouped by role?
0
 
LVL 7

Author Comment

by:Camillia
ID: 40469353
>I quote: "I want to get all the users with all the roles"
If no user can have all the roles, then you won't get any user with all the roles.

Do you want to get the users grouped by role?

No, I dont need it grouped. Just a grid with a list of users and their roles.
If a user doesn't have a role, in SQL, it can still be brought back with a Left Join. The "role" column will have nothing in it. I think that can be done with LINQ as well. That's what I wanted to try to begin with...join Users and Roles objects together.
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40469377
The following returns a collection of objects with properties User and Role (which can be null).
var users = _dataContext.Users.Select(user => new { User = user, Role = _dataContext.Roles.SingleOrDefault(role => user.Roles.Contains(role.RoleId)) });

Open in new window

0
 
LVL 7

Author Comment

by:Camillia
ID: 40469428
Thanks, Louisfr. I really appreciate it that you stayed with this ticket. Let me try it and will post back.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40470486
I get this error. There's no "role.RoleId". I see role.Name and role.Id.  Tried both but i get the same error.

(It's ok if we need to give up)
rolerror.png
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40470949
Not easy without the data definitions.

Instead of
user.Roles.Contains(role.RoleId)

Open in new window

you can try
user.Roles.Contains(role)

Open in new window

or
user.Roles.Any(userRole => userRole.RoleId == role.RoleId)

Open in new window

0
 
LVL 7

Author Comment

by:Camillia
ID: 40471031
I'll try it, thanks
0
 
LVL 7

Author Comment

by:Camillia
ID: 40472597
Just in case you're wondering, this one worked. Thank you so much for sticking with this question.
It gets all the user information..including role name and Id.

              var users = _dataContext.Users.Select(user => new { User = user, Role = _dataContext.Roles.FirstOrDefault(role => user.Roles.Any(userRole => userRole.RoleId == role.Id)) });

Open in new window

0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question