Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get item from dictionary by value of property

Tags:

c#

lambda

linq

I have a Dictionary<string, User>.

User is an object with the properties UID, UNIQUE KEY and more. My dictionary key is the UNIQUE KEY of the users.

Now, i want to get a User from my dictionary values by a UID and not the key, something like ContainsKey.. how its done with lambda expr or linq? is there a good solution for that?

like image 248
udidu Avatar asked Dec 23 '11 15:12

udidu


3 Answers

Here's a working sample:

using System;
using System.Collections.Generic;
using System.Linq;

internal class User
    {
        public string ID { get; set; }

        public string Name { get; set; }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Dictionary<string, User> dic = new Dictionary<string, User>();
            dic.Add("1", new User { ID = "id1", Name = "name1" });
            dic.Add("2", new User { ID = "id2", Name = "name2" });
            dic.Add("3", new User { ID = "id3", Name = "name3" });

            User user = dic.Where(z => z.Value.ID == "id2").FirstOrDefault().Value;

            Console.ReadKey();
        }
    }
like image 149
ken2k Avatar answered Oct 21 '22 04:10

ken2k


return dict.Single(x => x.Value.UID == target);

Of course, you might find that your design is questionable if it involves continually doing linear searches across a Dictionary.

like image 36
mqp Avatar answered Oct 21 '22 03:10

mqp


Of course you'll loose the benefit of having a dictionary, but you can do someting like:

var user = dict.Values.FirstOrDefault(k=>k.UID==xxxx);
like image 28
Felice Pollano Avatar answered Oct 21 '22 04:10

Felice Pollano