JL.
JL.

Reputation: 81262

Check for a unique value inside a collection using LINQ?

I have the following class definition:

public class PriorityItem
{
    public string uniqueID { get; set; }
    public List<DelegationTask> DelegationTasks = new List<DelegationTask>();
    public List<int> Priorities = new List<int>(); 
}

Now lets say I create a list from this class like this:

List<PriorityItem> pItems = new List<PriorityItem>();

And now I want to check for the presence of an item in this list based on the uniqueID property how is this done?

For example I will populate the list with a collection of PriorityItem, but only if the Priority item does not exist. To determine if it exists, I need to check using LINQ the value of uniqueID.

Hope this makes sense.

Upvotes: 2

Views: 677

Answers (2)

sgtz
sgtz

Reputation: 9009

Exists does the same thing as Any. Exists matches the SQL parlance a little more than Any does. Any and All naturally fit together as a kind of natural qualifier pair.

However in the sentence, "do we have this unique id?" Perhaps "exists" is a better fit in terms of readability and intention.

class Class1
{
    [Test]
    public void Test()
    {
        // initialise list
        var pItems = new List<PriorityItem>(){new PriorityItem(){uniqueID = "1"}, new PriorityItem(){uniqueID = "2"}, new PriorityItem(){ uniqueID = "123"}};
        var IDtoFind = "123";
        var wasFound = pItems.Exists(o => o.uniqueID == IDtoFind);
    }
}

public class PriorityItem
{
    public string uniqueID { get; set; }
    //public List<DelegationTask> DelegationTasks = new List<DelegationTask>();
    public List<int> Priorities = new List<int>();

}

Upvotes: 0

ColinE
ColinE

Reputation: 70122

The Any linq extension method returns true if any items are found which match a certain criteria. You can use it as follows:

string idToSearchFor = "123"
bool exists = pItems.Any(item => item.uniqueId == idToSearchFor);

With the above code exists will be true, only if your list contains a PriorityItem with the uniqueId of "123".

Upvotes: 5

Related Questions