Generalize a function - c#

I am trying to figure out if there is a way to generalize a function that takes a Hashset of two unrelated objects with similar attributes. I have some sample code below:
private IList<IDictionary<string, string>> BuildDictionary(HashSet<ClassA> ClassA)
{
IList<IDictionary<string, string>> data = new List<IDictionary<string, string>>();
foreach (var a in ClassA)
{
Dictionary<string, string> aDictionary = new Dictionary<string, string>();
aDictionary.Add(a.Code, a.Code + "," + a.Name);
data.Add(aDictionary);
}
return data;
}
private IList<IDictionary<string, string>> BuildDictionary(HashSet<ClassB> ClassB)
{
IList<IDictionary<string, string>> data = new List<IDictionary<string, string>>();
foreach (var b in ClassB)
{
Dictionary<string, string> bDictionary = new Dictionary<string, string>();
bDictionary.Add(b.Code, b.Code + "," + b.Name);
data.Add(bDictionary);
}
return data;
}
Thus as evident from the code, the two classes are not related but they both are in a HashSet and contain similar attributes (code, name). I have tried using the generic T but that failed due to the fact that I don't have the generic class T created. Would there be anyway to get around this issue without creating a new class?

If your source classes are sealed or can't be modified to a common interface, you can use accessors for the parts that are needed, as one might do in most LINQ queries.
Here's an example implementation. Note that toKey() and toMemberValue() could be named more appropriately, but this is enough to replicate what you are doing for any class where you can specify a lambda to retrieve the relevant property, and isn't dependent upon the class necessarily having the same property names so long as the lambda is written accordingly. Main() shows what it would look like to use this method for both cases.
public IList<IDictionary<string, string>> BuildDictionary<T>(HashSet<T> sourceSet, Func<T, string> toKey, Func<T, string> toMemberValue)
{
IList<IDictionary<string, string>> data = new List<IDictionary<string, string>>();
foreach (var element in sourceSet)
{
Dictionary<string, string> newLookup = new Dictionary<string, string>();
newLookup.Add(toKey(element), $"{toKey(element)},{toMemberValue(element)}");
data.Add(newLookup);
}
return data;
}
void Main()
{
HashSet<ClassA> setOfAs = new HashSet<ClassA>(new[] { new ClassA { Code = "foo", Name = "bar" }, new ClassA { Code = "foo2", Name = "bar2" } });
HashSet<ClassB> setOfBs = new HashSet<ClassB>(new[] { new ClassB { Code = "foo", Name = "bar" }, new ClassB { Code = "foo2", Name = "bar2" } });
var lookupOfAs = BuildDictionary(setOfAs, x => x.Code, x => x.Name);
var lookupOfBs = BuildDictionary(setOfBs, x => x.Code, x => x.Name);
}
// Define other methods and classes here
public class ClassA
{
public string Code { get; set; }
public string Name { get; set; }
}
public class ClassB
{
public string Code { get; set; }
public string Name { get; set; }
}

If you own the source code to both types you can implement a common interface.
private IList<IDictionary<string, string>> BuildDictionary<T>(HashSet<T> someHashSetOfTs) where T : ICommon
{
IList<IDictionary<string, string>> data = new List<IDictionary<string, string>>();
foreach (var a in someHashSetOfTs)
{
Dictionary<string, string> aDictionary = new Dictionary<string, string>();
aDictionary.Add(a.Code, a.Code + "," + a.Name);
data.Add(aDictionary);
}
return data;
}
Interface definition
public interface ICommon {
string Code {get; }
string Name {get; }
}
And now apply ICommon to both types ClassA and ClassB.

Related

Create a Dictionary from another Dictionary and a List<T> on a matching values

I have the following function, which takes a Dictionary and a List, matches rows in each of those and returns another Dictionary based on matcing items.
Is there a better way (code and performance -wise) to achieve the same result?
public sealed class ProdIds
{
public List<ProdID> Items { get; set; }
}
public sealed class ProdID
{
public string SpecialId { get; set; }
public int ItemId { get; set; }
}
Simplified view of the entries:
names: {100, "Name1"}, {333, "Name3"}, {212, "Name55"}, {99, "NameABC"}, ...
ids: {"SP44", 212}, {"SP33", 333}, {"SP11", 100}, {"SP9", 99}, ...
private static Dictionary<string, string> CreateMatchedDictionary (IReadOnlyDictionary<int, string> names, List<ProdIds> ids)
{
var dic = new Dictionary<string, string>();
foreach (var name in names)
{
foreach (var id in ids)
{
if (name.Key == id.Items[0].ItemId)
{
dic.Add(id.Items[0].SpecialId, name.Value);
}
}
}
return dic;
}
What I want to be returned here, is a new Dictionary which would look similar to this:
dic: {"SP44", "Name55"}, {"SP33", "Name3"}, {"SP11", "Name1"}, {"SP9", "NameABC"}, ...
The main performance problem is that you're looping through the names dictionary instead of taking advantage of the built-in O(1) lookup:
private static Dictionary<string, string> CreateMatchedDictionary (IReadOnlyDictionary<int, string> names, List<ProdIds> ids)
{
var dic = new Dictionary<string, string>();
foreach (var id in ids)
{
string name = null;
if (names.TryGetValue(id.Items[0].ItemId, out name)
{
dic.Add(id.Items[0].SpecialId, name);
}
}
return dic;
}
You could use Linq to make the code more concise, but it's not going to improve performance and might make debugging harder.

Selecting properties for building dynamic SQL queries

I really don't like to hard code the name of properties of my models. So I came up with this code so far. My code is working fine and it does exactly what I want but in an ugly way. I'm pretty sure it will be problematic soon. So any help to improve it and make it work in the right way is appreciated. I'm looking to fine better way to extract selected property names without converting expression body to string. Any change to any part of this class is fine with me. Even changing usage as long as I don't hard code my property names.
What is the better way to extract selected properties name of a model?
Here is my code:
public class Selector<T> : IDisposable
{
Dictionary<string, Func<T, object>> Selectors = new Dictionary<string, Func<T, object>>();
public Selector(params Expression<Func<T, object>>[] Selector)
{
foreach (var select in Selector)
{
//string MemberName = CleanNamesUp(select.Body.ToString());
//Func<T, object> NewSelector = select.Compile();
#region Ugly Part 1
Selectors.Add(CleanNamesUp(select.Body.ToString()), select.Compile());
#endregion
}
}
#region I am Doing This So I can Use Using(var sl = new Selector<T>())
public void Dispose()
{
Selectors.Clear();
Selectors = null;
}
#endregion
#region Ugly Part 2
private string CleanNamesUp(string nameStr)
{
string name = nameStr.Split('.')[1];
if (name.Contains(","))
{
name = name.Split(',')[0];
}
return name;
}
#endregion
public Dictionary<string, object> GetFields(T Item)
{
Dictionary<string,object> SetFieldList = new Dictionary<string, object>();
foreach(var select in Selectors)
{
SetFieldList.Add( select.Key , select.Value(Item));
}
return SetFieldList;
}
public List<Dictionary<string, object>> GetFields(IEnumerable<T> Items)
{
List<Dictionary<string, object>> SetFieldListMain = new List<Dictionary<string, object>>();
foreach (var item in Items)
{
Dictionary<string, object> SetFieldList = new Dictionary<string, object>();
foreach (var select in Selectors)
{
SetFieldList.Add(select.Key, select.Value(item));
}
SetFieldListMain.Add( SetFieldList);
}
return SetFieldListMain;
}
internal List<string> GetKeys()
{
return new List<string>(this.Selectors.Keys);
}
}
This is my model:
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool IsEnabled { get; set; }
public bool IsLocked { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime LockedAt { get; set; }
}
And I am using it like this:
User user1 = new User();
user1.Email = "testDev#gmail.com";
user1.UserName = "dora";
user1.Password = "123456";
var UpObject = new Selector<User>( x => x.UserName, x => x.Password, x => x.Email, x => x.IsEnabled );
Dictionary<string,object> result = UpObject.GetFields(user1);
You can avoid parsing the expressions as string if you instead parse them as System.Linq.Expressions.
Full code sample follows, but not exactly for your code, I used DateTime instead of the generic T, adapting should just be find&replace:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace ExprTest
{
class Program
{
static void Main(string[] args)
{
#region Usage
Expression<Func<DateTime, object>> propertySelector = x => x.Day;
Expression<Func<DateTime, object>> methodSelector = x => x.AddDays(1.5);
Expression[] inputSelectors = new Expression[] { propertySelector, methodSelector };
#endregion
//These are your final Selectors
Dictionary<string, Func<DateTime, object>> outputSelectors = new Dictionary<string, Func<DateTime, object>>();
//This would be in your Selector<T> constructor, replace DateTime with T.
//Instead of CleanNamesUp you would decide which part to use by extracting the appropriate Expression argument's Name.
foreach (Expression<Func<DateTime, object>> selectorLambda in inputSelectors)
{
Expression selectorExpression = selectorLambda.Body;
string name = null;
while (string.IsNullOrEmpty(name))
{
switch (selectorExpression)
{
#region Refine expression
//Necessary for value typed arguments, which get boxed by Convert(theStruct, object)
case UnaryExpression unary:
selectorExpression = unary.Operand;
break;
//add other required expression extractions
#endregion
#region Select expression key/name
case MemberExpression fieldOrProperty:
name = fieldOrProperty.Member.Name;
break;
case MethodCallExpression methodCall:
name = methodCall.Method.Name;
break;
//add other supported expressions
#endregion
}
}
outputSelectors.Add(name, selectorLambda.Compile());
}
//Set a breakpoint here to explore the outputSelectors
}
}
}
There could be a library for this, but i don't know about any, except PredicateBuilder for when you need to unify lambda arguments into one lambda expression.
I think maybe you forgot an important keyword 'nameof'. With the keyword, the code will be like this:
class User
{
public string Name { get; set; }
public string Address { get; set; }
public string Tel { get; set; }
}
static Dictionary<string, object> GetFieldsOf<T>(T item, params string[] args)
{
var properties = args.Select(property => typeof(T).GetProperty(property));
return properties.ToDictionary(property => property.Name, property => property.GetValue(item));
}
static void Main(string[] args)
{
var user = new User { Name = "Abel", Address = "Unknown", Tel = "XXX-XXX" };
var result = GetFieldsOf(user, nameof(User.Name), nameof(User.Address));
}
This code will result in some performance problems caused by reflection. But fortunately, you can avoid these by emitting a small segement of code.
//MSIL
ldarg.0
call Property.GetMethod
ret
And replace it with proerpty.GetValue. These code can be generated and cached per type, which is still worthwhile.

Cannot convert from custom object to object or dynamic

I have a List which I would like to populate with different types of objects, trying to do it with object\dynamic, but it doesn't, even when casting.
using asp.net core.
See my code:
public Dictionary<string, Employee> getEmployees(); //This method returns a dictionary of string as a key and Employee as a value.
public Dictionary<string, customer>()> getCustomers(); //same principal
public List<Dictionary<string, object>> getDifferentItems()
{
List<Dictionary<string, object>> listOfItems = new List<Dictionary<string, object>>();
listOfItems.add(getEmployees()); //Error
listOfItems.add(getCustomers()); //Error
return listOfItems;
}
Depending on what you are trying to do, I can see two solutions:
Create a list of TWO different dictionaries
public Dictionary<string, Employee> getEmployees() {
return new Dictionary<string, Employee>();
}
public Dictionary<string, Customer> getCustomers() {
return new Dictionary<string, Customer>();
}
public List<Dictionary<string, object>> getDifferentItems()
{
List<Dictionary<string, object>> listOfItems = new List<Dictionary<string, object>>();
listOfItems.Add(this.getEmployees().ToDictionary(entry => (string)entry.Key,
entry => (object)entry.Value));
listOfItems.Add(this.getCustomers().ToDictionary(entry => (string)entry.Key,
entry => (object)entry.Value));
return listOfItems;
}
Create one dictionary with all the values
public Dictionary<string, Employee> getEmployees() {
return new Dictionary<string, Employee>();
}
public Dictionary<string, Customer> getCustomers() {
return new Dictionary<string, Customer>();
}
public Dictionary<string, object> getDifferentItems()
{
Dictionary<string, object> listOfItems = new Dictionary<string, object>();
foreach (var entry in getEmployees()) {
listOfItems.Add(entry.Key, entry.Value);
}
foreach (var entry in getCustomers()) {
listOfItems.Add(entry.Key, entry.Value);
}
return listOfItems;
}
There are a couple of issues here, both related to variance.
This won't work because List<T>, or any other class in .NET for that matter, does not support variance.
In other words T has to be a specific type, and does not respect inheritance / substitutability as with non-generic types.
Similarly, for Dictionary<TKey, TValue>, TValue is not variant, so you can't simply use object as the value.
IEnumerable<out T> on the other hand is covariant so you could do this:
public IEnumerable<IDictionary> getDifferentItems()
{
yield return getEmployees();
yield return getCustomers();
}
IDictionary is used, as it is the only common ancestor (other than object) to Dictionary<string, Employee> and Dictionary<string, Customer>.
This may satisfy your requirements, but you don't make clear whay you are trying to achive with your getDifferentItems method.
More information on variance can be found here.
I'd personally make an interface, such as IPerson that has all the properties of Employees and Customers, such as Name, Address, ID, etc.
Set up your Customer and employee classes to implement IPerson
Then use a IPerson in your dictionary and you can add to the objects to that.
Here's some code:
public class Employee : IPerson
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Customer : IPerson
{
public int ID { get; set; }
public string Name { get; set; }
}
public interface IPerson
{
int ID { get; set; }
string Name { get; set; }
}
public class Test
{
public void MyTest()
{
List<Dictionary<string, IPerson>> listOfItems = new List<Dictionary<string, IPerson>>();
Dictionary<string, IPerson> myEmployees = new Dictionary<string, IPerson>();
string someString = "blah";
Employee e = new Employee();
e.Name = "Bob";
e.ID = 1;
myEmployees.Add(someString, e);
Dictionary<string, IPerson> myCustomers = new Dictionary<string, IPerson>();
string someOtherString = "blah";
Customer c = new Customer();
c.Name = "Robert";
c.ID = 2;
myCustomers.Add(someOtherString, c);
listOfItems.Add(myEmployees);
listOfItems.Add(myCustomers);
}
}
Here is another solution :
public class Test
{
Dictionary<string, object> listOfItems = new Dictionary<string, object>();
List<Employee> employees = new List<Employee>();
List<customer> customers = new List<customer>();
public Dictionary<string, object> getEmployees()
{
return employees.GroupBy(x => x.name, y => (object)y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
}//This method returns a dictionary of string as a key and Employee as a value.
public Dictionary<string, object> getCustomers()
{
return customers.GroupBy(x => x.name, y => (object)y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
} //same principal
public Dictionary<string, object> getDifferentItems()
{
listOfItems = getEmployees();
listOfItems.Concat(getCustomers());
return listOfItems;
}
}
public class Employee
{
public string name { get;set;}
}
public class customer
{
public string name { get;set;}
}

map entity to runtime created dto

Is there an automagic (automapper?) way to map an entity to a runtime created dynamic object with properties passed as parameters? I want to do an API where the clients can select the properties of the entities they want to fetch.
I mean:
class Patient
{
public int PatientId{ get; set; }
public string Name{ get; set; }
public string LastName{ get; set; }
public string Address{ get; set; }
...
}
getPatient(string[] properties)
{
//Return an object that has the properties passed as parameters
}
Imagine you only want to fetch a PatientDTO with PatientId and Name:
getPatient(new string[]{"PatientId", "Name"}
should return
{
"PatientId": "1234",
"Name": "Martin",
}
and so on.
For now I'm doing it with Dictionary, but probably there is a better way. This is my approach:
For a single object:
public static Dictionary<string, object> getDTO(string[] properties, T entity)
{
var dto = new Dictionary<string, object>();
foreach (string s in properties)
{
dto.Add(s, typeof(T).GetProperty(s).GetValue(entity));
}
return dto;
}
For a list of objects:
public static List<Dictionary<string, object>> getDTOList(string[] properties, List<T> TList)
{
var dtoList = new List<Dictionary<string, object>>();
foreach(T entity in TList)
{
dtoList.Add(getDTO(properties, entity));
}
return dtoList;
}
Thank you.
How about creating a new dynamic object based solely on the specified property fields and returning the dynamic?
You will need to add using statements for: System.Dynamic and System.ComponentModel for the following to work.
public static dynamic getDTO(object entity, string[] properties)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (var p in properties)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(entity.GetType()))
{
if (property.Name == p)
{
expando.Add(p, property.GetValue(entity));
break;
}
}
}
return expando as ExpandoObject;
}
Calling this method would look something like this:
var patient = new Patient() { PatientId = 1, Name = "Joe", LastName = "Smith", Address = "123 Some Street\nIn Some Town, FL 32333" };
var propList = new string[] { "PatientId", "Name", "Address" };
dynamic result = getDTO(patient, propList);
Console.WriteLine("Id:{0} Name: {1}\nAddress: {2}", result.PatientId, result.Name, result.Address);
Console.ReadLine();

Dictionary <string,string> map to an object using Automapper

I have a class like
public User class
{
public string Name{get;set;}
public string Age{get;set;
}
With a dictionary like
Dictionary<string,string> data= new Dictionary<string,string>();
data.Add("Name","Rusi");
data.Add("Age","23");
User user= new User();
Now i want to map User object to this dictionary using Automapper. Automapper maps properties of objects but in my case there is a dictionary and object.
How can this be mapped?
AutoMapper maps between properties of objects and is not supposed to operate in such scenarios. In this case you need Reflection magic. You could cheat by an intermediate serialization:
var data = new Dictionary<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var serializer = new JavaScriptSerializer();
var user = serializer.Deserialize<User>(serializer.Serialize(data));
And if you insist on using AutoMapper you could for example do something along the lines of:
Mapper
.CreateMap<Dictionary<string, string>, User>()
.ConvertUsing(x =>
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<User>(serializer.Serialize(x));
});
and then:
var data = new Dictionary<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var user = Mapper.Map<Dictionary<string, string>, User>(data);
If you need to handle more complex object hierarchies with sub-objects you must ask yourself the following question: Is Dictionary<string, string> the correct data structure to use in this case?
This thread is a bit old, but nowadays there's how to do it on automapper without any configuration, as stated at official documentation:
AutoMapper can map to/from dynamic objects without any explicit configuration (...) Similarly you can map straight from Dictionary to objects, AutoMapper will line up the keys with property names.
Update:
The following code shows a working sample (with unit tests).
void Test()
{
var mapper = new MapperConfiguration(cfg => { }).CreateMapper();
var dictionary = new Dictionary<string, object>()
{
{ "Id", 1 },
{ "Description", "test" }
};
var product = mapper.Map<Product>(dictionary);
Assert.IsNotNull(product);
Assert.AreEqual(product.Id, 1);
Assert.AreEqual(product.Description, "test");
}
class Product
{
public int Id { get; set; }
public string Description { get; set; }
}
With the current version of AutoMapper:
public class MyConfig
{
public string Foo { get; set; }
public int Bar { get; set; }
}
var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();
var source = new Dictionary<string, object>
{
["Foo"] = "Hello",
["Bar"] = 123
};
var obj = mapper.Map<MyConfig>(source);
obj.Foo == "Hello"; // true
AutoMapper is quite a flexible solution. You could probably achieve this using a custom mapping profile, e.g.:
public class UserMappingProfile : Profile
{
// Props
public override string ProfileName { get { return "UserMappingProfile"; } }
// Methods
public override void Configure()
{
CreateMap<User, Dictionary<string, string>>().ConvertUsing<DictionaryTypeConverter>();
base.Configure();
}
// Types
internal class DictionaryTypeConverter : ITypeConverter<User, Dictionary<string, string>>
{
public User Convert(ResolutionContext context)
{
var dict = context.SourceValue as Dictionary<string, string>;
if (dict == null)
return null;
return new User() { Name = dict["Name"], Age = dict["Age"] };
}
}
}
With this, I can create a custom instance of a mapper:
var config = new Configuration(new TypeMapFactory(), MapperRegistry.AllMappers());
config.AddProfile<UserMappingProfile>();
config.AssertConfigurationIsValid();
var mapper = new MappingEngine(config);
Which I could probably do:
var dict = new Dictionary<string, string> { { "Name", "Matt" }, { "Age", "27" } };
var user = mapper.Map<User, Dictionary<string, string>>(dict);
Much simpler solution. Just map your object from KeyValuePair. Example:
CreateMap<KeyValuePair<Guid, string>, User>()
.ForMember(u => u.Id, src => src.MapFrom(x => x.Key))
.ForMember(u => u.Name, src => src.MapFrom(x => x.Value));
This will work if your function type is "ExpandoObject".
public EmpClass
{
public string EmpName { get; set; }
public int EmpId { get; set; }
}
this.CreateMap<IDictionary<string, object>, EmpClass>()
.ForMember(dest => dest.EmpName, src => src.MapFrom(x => x["EmpName"]))
.ForMember(dest => dest.EmpId, src => src.MapFrom(x => x["EmpId"]));
Let me know if it helps.
Apparently recent AutoMapper doesn't work with Dictionary<string, string>, must be Dictionary<string, object> without map defined
must be Dictionary<string, object> without CreateMap

Categories

Resources