Skip to content

Instantly share code, notes, and snippets.

@jskeet
Created July 18, 2022 14:23
Show Gist options
  • Select an option

  • Save jskeet/40d5b5b88fc33281ce4afa43ae52e698 to your computer and use it in GitHub Desktop.

Select an option

Save jskeet/40d5b5b88fc33281ce4afa43ae52e698 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
public class MyEntity
{
public string Name;
public string MacAddress;
public bool IsIncredible;
public DateTime LastConnection;
public long Id { get; set; }
public MyEntity(long id, string name, string macAddress, bool isIncredible, DateTime lastConnection)
{
Id = id;
Name = name;
MacAddress = macAddress;
IsIncredible = isIncredible;
LastConnection = lastConnection;
}
}
public class Program
{
public static void Main()
{
MyEntity element1 = new MyEntity(10, "ghuilobiukg", "E5:AB:4C:D3:24:68", true, new DateTime());
MyEntity element2 = new MyEntity(5422, "qsdlkjfhmsssszzzz", "F1:7D:89:3E:AB:87", false, new DateTime());
ConcurrentDictionary<string, MyEntity> myTab = new ConcurrentDictionary<string, MyEntity>();
myTab.GetOrAdd(element1.Id.ToString(), element1);
myTab.GetOrAdd(element2.Id.ToString(), element2);
var element = FindEntity<MyEntity>(myTab, "IsIncredible", true);
}
public static T FindEntity<T>(ConcurrentDictionary<string, T> dictionary,
string fieldName, dynamic value)
where T : class
{
FieldInfo[] fields = typeof(T).GetFields(); // Just to see what you can get
FieldInfo fieldFound = typeof(T).GetField(fieldName);
if (fieldFound == null)
{
Console.Write("field not found into class\n");
return null;
}
return (from Item in dictionary
where fieldFound.GetValue(Item.Value) == value
select Item.Value).First();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment