I’ve 3 different database tables that have the same 5 fields but those does not have any foreign key relation as they are not keeping the same value in fact, but the equivalents; like: CompanyA table has productA and CompanyB has productB.
so I have 3 different collections include 3 fields that are equivalent. So what I’d like to do is to use a single class that has companyType and ProductName properties and use only one method to cast those 3 different collections to one and only class object, say ResultClass.
public class ResultClass
{
public EnumCompanyType CompanyType { get; set; }
public string ProductName { get; set; }
public ICollection<ResultClass> ConvertAnything(ICollection<T> collection)
{
//Cast it to ResultClass
return resultClassCollection;
}
}
So that I can use this like:
ICollection<ProductA> aCollection = GetCompanyAData();
ICollection<ProductB> bCollection = GetCompanyBData();
ConvertAnything(aCollection);
ConvertAnything(bCollection);
I’ve tried “dynamic” but actually don’t know the principle (neither have the knowledge); so I’ve messed it up and I think it’s not for this stuff.
I’ve tried to create an extension method but since the extension has no type for its parameter (as it is using ICollection), I can’t access the fields of the items (eg. properties)
I’m using LinqToSql and all the database table terms etc. belongs to this concept, nothing else.
edit:
I think I should made myself clear:
The multiple instances that I’m trying to avoid (or shouldn’t I, still thinking) is like below
public ICollection<ResultClass> ConvertAnythingForA(ICollection<ProductA> collection)
{
foreach(var item in collection)
{
var result = new ResultClass
{
ProductName = item.ProductA,
ProductType = EnumProductType.ProductA
};
resultClassCollection.Add(result);
}
return resultClassCollection;
}
public ICollection<ResultClass> ConvertAnythingForB(ICollection<ProductB> collection)
{
foreach(var item in collection)
{
var result = new ResultClass
{
ProductName = item.ProductB,
ProductType = EnumProductType.ProductB
};
resultClassCollection.Add(result);
}
return resultClassCollection;
}
Thanks in advance.
I may not be understanding you completely, but since ProductA, ProductB etc have the same signature it seems like you’d want an interface like
And have those classes just implement the interface. You could work with collections of the interface that could have objects of the various types. If you need a convert anything method, it would look like
After comments- I see you that you are getting a non generic ICollection. Did you try something like this: