Avatar of lapucca
lapucca
 asked on

How to built-in sort generic collection using one of the attribute?

Hi, I'm using vs2012
I have a collection, List<UserPrincipal>.  How can I use the the buit-in collection Sort function to sort the collection based on one of the attribute of UserPrincipal (SamAccountName)?  Looked at MSDN but didn't see any example code on how to do this.

Thank you.
C#

Avatar of undefined
Last Comment
lapucca

8/22/2022 - Mon
it_saige

This works for me:
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;

namespace EE_Q28585582
{
	class Program
	{
		private static List<UserPrincipal> users = new List<UserPrincipal>();

		static void Main(string[] args)
		{
			PrincipalContext context = new PrincipalContext(ContextType.Domain);
			UserPrincipal user = new UserPrincipal(context);
			PrincipalSearcher searcher = new PrincipalSearcher(user);
			foreach (Principal result in searcher.FindAll())
			{
				UserPrincipal upe = result as UserPrincipal;
				if (upe != null)
					users.Add(upe);
			}

			foreach (UserPrincipal up in users)
				Console.WriteLine(up.Name);
			Console.ReadLine();

			var usort = (from up in users orderby up.SamAccountName select up);
			foreach (UserPrincipal up in usort)
				Console.WriteLine(up.Name);
			Console.ReadLine();
		}
	}
}

Open in new window


-saige-
ASKER CERTIFIED SOLUTION
Carl Tawn

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
kaufmed

*No Points*

Slightly shorter version of Carl's suggestion:

list.Sort((left, right) => string.Compare(left.SAMAccountName, right.SAMAccountName));

Open in new window

lapucca

ASKER
Carl,
That works great thank you.
Kaufmed, Your loc gives red underline.  Error message says can't convert because it's not delegate.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
kaufmed

It's possible you may need to include the type as well--usually you don't have to.

e.g.

list.Sort((UserPrincipal left, UserPrincipal right) => string.Compare(left.SAMAccountName, right.SAMAccountName));

Open in new window

kaufmed

That's what I get for trying to do it from memory  ; )

Corrected:

s.Sort((left, right) => { return string.Compare(left.SamAccountName, right.SamAccountName); });

Open in new window

lapucca

ASKER
Hi, I have a new question related to this one, ID: 28586081
Appreciate it if you can have a look.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.