SingleOrDefault Sequence contains more than one matching element

I was receiving an exception “SingleOrDefault Sequence contains more than one matching element” when trying to return a single object from a List. Here is a little demonstration of what was happening. First, my very useful, real-life class:

    public class Testing
    {
        public string Name{ get; set; }
        public int ID { get; set; }

        public Testing(string name, int id)
        {
            Name = name;
            ID = id;
        }
    }

So in the Page_Load event, I populate my useful, real-life class with some very important data. This is very secure data, so don’t share it with anyone:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));

            var item = testing.SingleOrDefault(i => i.ID == 1);
        }

If all my IDs are unique, no problem, this will run successfully. If, however, I have duplicate IDs, then problem will arise. So if I change my code to that below, adding a duplicate ID:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));
            testing.Add(new Testing("new york", 1));

            var item = testing.SingleOrDefault (i => i.ID == 1);
        }

Bong, I get the error “SingleOrDefault Sequence contains more than one matching element”.
The way I got around this was to replace SingleOrDefault with FirstOrDefault, and my code ran correctly:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));
            testing.Add(new Testing("new york", 1));

            var item = testing.FirstOrDefault (i => i.ID == 1);    
        }
Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: