Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use LINQ to check if objects in a list have a unique ID?

Tags:

c#

object

list

linq

say I have a list containing objects like this one:

public class Person
{
    private string _name; 
    private string _id;
    private int _age;

    public Person 
    {
    }

    // Accessors
}

public class ManipulatePerson
{
    Person person = new Person();
    List<Person> personList = new List<Person>;

    // Assign values

    private void PopulateList();
    {
        // Loop 
        personList.Add(person);

        // Check if every Person has a unique ID
    }
}

and I wanted to check that each Person had a unique ID. I would like to return a boolean true/false depending on whether or not the IDs are unique. Is this something I can achieve with LINQ?

like image 540
Jack Avatar asked Feb 19 '16 15:02

Jack


2 Answers

Note that you can even leverage directly an HashSet<>:

var hs = new HashSet<string>();
bool areAllPeopleUnique = personList.All(x => hs.Add(x.Id));

(and is the code that I normally use)

It has the advantage that on the best case (presence of some duplicates) it will stop before analyzing all the personList collection.

like image 141
xanatos Avatar answered Sep 22 '22 19:09

xanatos


I would use Distinct and then check against the counts for example:

bool bAreAllPeopleUnique = (personList.Distinct(p => p.ID).Count == personList.Count);

However as @Ian commented you will need to add a property to the Person class so that you can access the Id like so:

public string ID
{
    get { return _id; }
}

A 'nicer' way to implement this would be to add a method like so:

private bool AreAllPeopleUnique(IEnumerable<Person> people)
{
    return (personList.Distinct(p => p.ID).Count == personList.Count);
}

NOTE: The method takes in an IEnumerable not a list so that any class implementing that interface can use the method.

like image 41
TheLethalCoder Avatar answered Sep 20 '22 19:09

TheLethalCoder