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?
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();
}
}
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With