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
SolvedPrivate

Anyway to have 2 "contains" in this LINQ?

Posted on 2014-11-24
22
60 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
  • 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 33

Accepted Solution

by:
it_saige earned 250 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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 33

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 250 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

837 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