Reference known property in (List<someClass>)someObject - c#

have tried some searches. Probably my lack of knowledge that I'm not using the right search terms or perhaps just not understanding the answers.
I have a method that is being passed an object, which I want to output a particular value to a text file.
I already know the object will be a List< someClass > of a few different possible classes (customers/employees/items etc). But all of the classes contain the same string property (e.g.) string idNumber.
So something like this:
public static void OutputFile(object myInput)
{
foreach (someGenericObject in (List<anyType>)myInput)
{
string textToOutput = someGenericObject.idNUmber;
//output the text to somewhere else here
}
}
I feel like as long as I know that it will always contain a this "idNumber" property regardless of the type, that I should be able to reference it somehow. But I just can't seem to get my head around it?
The error I typically get is something like:
Cannot cast List< Employee > to List< object > etc.
Thanks in advance

As I suggested in the comments, if you have the ability to modify these classes, you can have them all inherit from an interface IHasIdNumber with an idNumber property.
Your method would then become:
public static void OutputFile(IEnumerable<IHasIdNumber> myInput)
{
foreach (var item in myInput)
{
string textToOutput = item.idNUmber;
//output the text to somewhere else here
}
}

There are a few ways you can solve this.
Recommended way: Implement common interface:
public interface INumberable { // I'm sure you can come up with a better name...
string IDNumber { get; set; }
}
And then all the possible classes that can be passed into the method will implement INumberable. Your method can then look like this:
public static void OutputFile(List<INumerable> myInput)
{
foreach (var someGenericObject in myInput)
{
string textToOutput = someGenericObject.idNUmber;
//output the text to somewhere else here
}
}
Not-so-recommended way: Reflection:
Type t = someGenericObject.GetType();
var p = t.GetProperty("idNumber");
string theStringYouWant = (string)p.GetValue(someGenericObject);
Note that this is not very safe.

You can use [dynamic].
foreach (var someGenericObject in (dynamic)myInput)
{
//...
}

If all your classes have the same property you want to access in foreach loop you can do in via interface.
public interface ISmth {
int MyProperty { get; set; }
}
public class Student : ISmth {
public int MyProperty { get; set; }
}
public class Employee : ISmth {
public int MyProperty { get; set; }
}
public static void DoSmth(object myObj) {
foreach(ISmth item in (List<object>)myObj) {
Console.Write(item.MyProperty);
}
}
List<Student> stdList = new List<Student>();
DoSmth(stdList.Cast<object>().ToList());

Related

How to create the correct inherited class based on what is stored in the database

What Utility or Pattern can be used to solve this Issue? I don't know what can be used to assist with this. Can we use some type of pattern?
If you have the following abstract class:
abstract class Foo
{
function void Something()
{
// Get the media type
}
}
And the following classes that derive from that class:
class Foo1 : Foo
{
public string MyId {get;set}
public string MyFile {get;set}
public TxtFile MyTextFile {get;set}
function void myFooFunction()
{
// Save File to Txt
}
}
class Foo2 : Foo
{
public string MyId {get;set}
public string MyFile {get;set}
public XMLFile MyXMLFile {get;set}
function MyOtherFunction()
{
// Save to XML
}
}
Then in Linq (or Similar) within the repository you do something like this:
var a = (from e in db.myTable
where e.myFileType == "XML"
Select e);
Then we have to map this to the correct object. Like this:
Foo newFoo = FooFactory.CreateFooFor(a.myFileType.ToString())
newFoo.MyId = a.id;
newFoo.MyFile = a.myfile;
newFoo.MyXMLFile = a.xml;
The Factory certainly helps, but how do you do this for multiple "FileTypes" like txt for example? The Fields wouldn't match up!
Do I have to write more code that does the same thing??
I feel like there has to be something that can do this.
First, if myFooFunction and MyOtherFunction are both used to save, you can use the strategy pattern and just define and abstract Save() method to implement in derived classes. You might also look at the Template Method pattern.
Although this isn't exactly a pattern, you might also want to apply the "Pull Up Field" refactoring here and put the MyId and MyFile properties in the parent class.
For creation...
The Builder pattern is similar to the factory, but allows for more complex object creation. I don't know how well it fits this simplified example, but it might fit what you are actually trying to do in your real code. Probably not. I just mention it first because it is the closest to factory in my mind.
There are also the Mapper Pattern and the Data Mapper Pattern. You might encapsulate the mapping in an object and have the factory return a mapper:
FooMapper mapper = FooMapperFactory.CreateFooMapperFor(a.myFileType);
Foo newFoo = mapper.CreateFoo(a);
I believe you could solve your problem using generics. I took the liberty of changing around some code. Would this work?
public abstract class Foo
{
public abstract void Save();
public void Something()
{
// Get the media type
}
}
public class FooText : Foo
{
public string MyId { get; set; }
public string MyFile { get; set; }
public string MyTextFile { get; set; }
public override void Save()
{
// Save File to Txt
}
}
public class FooXml : Foo
{
public string MyId { get; set; }
public string MyFile { get; set; }
public string MyXMLFile { get; set; }
public override void Save()
{
// Save to XML
}
}
public class FooFactory<T> where T : Foo, new()
{
public static T CreateFoo()
{
return new T();
}
}
If you consider using reflection on the data that's returned from the database, or perhaps the Adapter pattern you can set up a dynamic way to map fields to each other. Using reflection (the following is pseudo logic as reflection is kind of messy code to provide):
Get a list of PropertyInfo objects for all public properties from the target type
Get a list of PropertyInfo objects for all public properties from the database type
Compare their names/types to create the mapping
Assign values from the database type, using reflection, to the target type
Something like this will do the trick:
public void AssignAndMapTypes<DatabaseType, TargetType>(DatabaseType db, ref TargetType target)
{
var dbType = db.GetType();
var dbTypeProperties = dbType.GetProperties(System.Reflection.BindingFlags.Public);
var targetType = target.GetType();
var targetTypeProperties = targetType.GetProperties(System.Reflection.BindingFlags.Public);
foreach (var prop in targetTypeProperties)
{
var matchingProp = dbTypeProperties.Where(e => { return (string.Compare(e.Name, prop.Name, true) == 0) && (e.PropertyType == prop.PropertyType) }).FirstOrDefault();
if(matchingProp != null)
{
prop.SetValue(target, matchingProp.GetValue(db, null), null);
}
}
}

List which accept only few types

Does there exist in any System namespace in C# a container, which can accept only some types?
For example I want to create my list in which I'll have only objects with type Class1 and int:
//accept only type Class1 and int;
MYLIST lst = new MYLIST(typeof(Class1), typeof(int));
lst.Add( 23 ); // OK
lst.Add( new Class1() ); // OK
lst.Add( "text" ); // wrong, not accepted type
Is something like that in .NET or I have to write it on my own? Thanks.
The C# type system does not allow you to express something like "either Class1 or int". Having said that, you can use overloads to get half of the way there:
class MyClass
{
private List<object> _items = new List<object>();
public void Add(int value) { _items.Add(value); }
public void Add(Class1 value) { _items.Add(value); }
...
}
The real tricky question is how you get things out, rather than how you put things in. There are several possibilities: get everything out as object (by implementing IEnumerable<object>), and maybe special methods like GetInt(int index) and GetClass1(int index).
The answer is NO, there is NO such list in C# and for VERY GOOD reason.
You could make a wrapper, but i'd advise against it.
public class CustomListWrapper< T, F>
{
private readonly List<object> internalList;
public CustomListWrapper()
{
this.internalList = new List<object>();
}
public void Add(object item)
{
if(!(item is T || item is F))
throw new Exception();
this.Add(item);
}
}
PS: before the downvote, for how to get the object out...well this is why this is a fairly bad idea, but you'd have to do an "is" on the type you get out to be able to cast it to the proper type.
Again, not exactly sure why you would EVER need to do this.
No. You will have to create your own. You can implement ICollection or IEnumerable or IList or whatever. You have lots of flexibility here. But bottom line, the answer is no, no such collection exists that allows you to limit the types in the collection to certain types automatically.
You cannot achieve this in a direct way. The item type of a List<T> must be a base type common to all the types you want to add to the list.
You could have a List<object> or a wrapper around a List<object> of cause. However, you would have to check at runtime if the items added to it are of the correct types and you would have to cast the items that you retrieve from the list to the correct type.
If you want to store different types in the same list, a good option would be to create an interface that all of these types must implement
public interface ICommonInterface
{
int Number { get; }
string Text { get; }
}
public Class1 : ICommonInterface
{
public int Number { get; set; }
public string Text { get; set; }
public string AnAdditionalProperty { get; set; }
}
public NumberWrapper : ICommonInterface
{
public NumberWrapper (int number)
{
this.Number = number;
this.Text = number.ToString();
}
public int Number { get; private set; }
public string Text { get; private set; }
}
public TextWrapper : ICommonInterface
{
public TextWrapper (string text)
{
this.Text = text;
int i;
Int32.TryParse(text, out i);
this.Number = i;
}
public int Number { get; private set; }
public string Text { get; private set; }
}
Then you can declare your list as
List<ICommonInterface> lst = new List<ICommonInterface>();
lst.Add(new Class1());
lst.Add(new NumberWrapper(77));
lst.Add(new TextWrapper("hello"));
Console.WriteLine(lst[0].Text);
why not just wrap a List<>, and make two add methods, one that accepts int, another that accepts Class1

How to compare objects in C#

How do you compare objects in C#. Here is a sample of my code
namespace MyService
{
public static class CurrentVCobj
{
public static string id { get; set; }
public static string Month { get; set; }
public static string Year { get; set; }
}
public static class ResponseVCObj
{
public static string id { get; set; }
public static string Month { get; set; }
public static string Year { get; set; }
}
}
I would like to assign values to the above objects (CurrentVCobj and ResponseVCObj) then compare(TRUE OR FALSE) them in the method below to see if they are equal
public static void compareMethood(IEnumerable<tets> vc )
{
var myvar = vc;
var mycac = rep.populateDict();
foreach (var item in myvar)
{
ResponseVCObj.id = item.id;
ResponseVCObj.Month = DateRange.Month;
ResponseVCObj.Year = DateRange.Year;
CurrentVCobj.id = currentV.Select(d => d.Value.id).ToString() ;
CurrentVCobj.Month = currentV.Select(d => d.Value.Month).ToString();
CurrentVCobj.Year = currentV.Select(d => d.Value.Year).ToString();
//COMPARE OBJECTS HERE
}
}
Try this:
if (ResponseVCObj.Equals(CurrentVCobj))
{
...
}
else
{
...
}
First off, is there any reason you are using static classes? Your sample code seems very bizarre to me. Your usage of LINQ seems unnecessary as well.
If you want to compare two different objects by something other than a simple reference check you need to override the Equals method.
A guide on that can be found here:
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
The other answers are correct in noting that you should override object.Equals, and that you should remove the static modifier from the classes and their members.
In addition, you should consider
having the classes inherit from the same interface
having the classes inherit from the same base class; if this is possible, then you can implement the equality comparison in that base class
implementing IEquatable on each class or the base class; if there's no common base type then you probably want to implement it twice on each type -- IEnumerable<CurrentVCobj> and IEnumerable<ResponseVCObj>
the fact that when you compare strings for equality, the results may vary from one computer to the other, depending on the culture settings on that computer.

Get collection property of a specific type

I have a class MyDatabaseContext that has a series of DbSet collection properties:
public DbSet<EntityA> EntitiesA { get; set; }
public DbSet<EntityB> EntitiesB { get; set; }
public DbSet<EntityC> EntitiesC { get; set; }
I need to get the name of the collection given the type of the entity.
For example, I have "EntityB" and want to get as a result "EntitiesB".
I really wanted to avoid switch-case statements, since MyDatabaseContext is generated automatically (T4 templates).
if you just want the name of the property here you go. I would just refine the answer given by hunter. You can use the same method with string as return type.
public string GetEntitiName<T>() where T : class
{
PropertyInfo propInfo = typeof(MyDatabaseContext).GetProperties().Where(p => p.PropertyType == typeof(DbSet<T>)).FirstOrDefault();
string propertyName = propInfo.Name; //The string has the property name ..
return propertyName;
}
I tried a sample similar to your situation. Try replacing List with DbSet.
class Program
{
public static void GetEntities<T>() where T : class
{
var info = typeof(TestClass1).GetProperties().Where(p => p.PropertyType == typeof(List<T>));
Console.WriteLine(info.FirstOrDefault().Name);
}
static void Main(string[] args)
{
GetEntities<int>();
Console.ReadLine();
}
}
public class TestClass1
{
public List<int> IntTest { get; set; }
public List<double> DoubleTest { get; set; }
public List<string> IStringTest { get; set; }
}
This sample works.
I know this is old page, But my answer maybe useful for other guys referring here. (like me)
I think you want to accessing EntitiesB to run a query on it, like EntitiesB.Where(a=>a.bla=="blabla"). If I'm right or another visitor of this page needs something like this, just easily use the following code:
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>()
Description:
_dbContext is Context class inherting from DbContext.
EntitiesB is DbSet<EntityB> defined in Context class.
Example:
Ilist result = ((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>().Where(b=>b.bla=="blabla").ToList();
Your generated file is a partial class, you could create a new file and declare a class with same name using the keyword partial, then make a method which will return the desired Collection...
I haven't actually done this myself, but it sounds like what you want to do is to use reflection to locate the property of type "DbSet" that has the appropriate generic type parameter. The following pseudo-C# should get you started:
foreach ( FieldInfo field in this.GetType() )
{
if ( field.FieldType.IsGenericType )
{
foreach ( Type param in field.FieldType.GetGenericArguments() )
{
if ( param.Name == soughtType )
{
return field.Name;
}
}
}
}

How to create a property for a List<T>

private List<T> newList;
public List<T> NewList
{
get{return newList;}
set{newList = value;}
}
I want to create something like this, but this is won't work. it's just an example to demonstrate my goal as it's pretty common creating proprties for string and int and even T but I've never seen a List property
Is it even possible do such a thing, creating a property for type List ?
EDIT
I have a normal class that has normal properties (string properties, int properties, etc) but I have this property that stores user options, So on the presentation layer I had to convert them into a string so I could be able to store them in the Object. Now is it possible to have a property of type List to store the multivalues in a better and clean way, instead of converting information into one string and then split it and again join it! Thanks Again =D
EDIT2
private List<KeyValuePair<string, string>> _settings;
public List<KeyValuePair<string, string>> MySettings
{
get { return _settings; }
set { _settings = value; }
}
I used the exact code you posted but the property still won't appear in the object's instance, so I tried adding code in the get and set (I wonder why you left them empty or does it means something?) and also added a private variable in the class but still it doesn't appear in the properties of the object's instance!
I hope you could provide the exact code to implement this property and a simple code that assigns or retrieves from/to an instance of this class object
It's the first time to even hear about this KeyValuePair and all the tutorials are pretty simple and not for my case, sorry!
The Last Edit: After a lot of researching and the help of Mark Avenius I found the perfect answer. hope everyone can benefit from this.
NOW! HOW TO CREATE A PROPERTY FOR A LIST :
The Options Class
Public Class Options
{
private string id;
private int option;
public int ID
{
get { return id; }
set { id= value; }
}
public string Option
{
get { return option; }
set { option = value; }
}
}
The Users Class
public class Users
{
private int userId;
private string pass;
private List<Options> userOptions = new List<Options>();
public int ID
{
get { return userId; }
set { user = userId; }
}
public string Pass
{
get { return pass; }
set { pass = value; }
}
public List<Options> OptionsList
{
get { return userOptions; }
set { userOptions = value; }
}
}
The Presentation Layer
Users newUser = new Users ();
Options userOption = new Options ();
userOption.ID = int.Parse(txtBxID.Text);
userOption.Option = txtBxOption.Text;
Item.Options.Add(userOption);
T must be defined within the scope in which you are working. Therefore, what you have posted will work if your class is generic on T:
public class MyClass<T>
{
private List<T> newList;
public List<T> NewList
{
get{return newList;}
set{newList = value;}
}
}
Otherwise, you have to use a defined type.
EDIT: Per #lKashef's request, following is how to have a List property:
private List<int> newList;
public List<int> NewList
{
get{return newList;}
set{newList = value;}
}
This can go within a non-generic class.
Edit 2:
In response to your second question (in your edit), I would not recommend using a list for this type of data handling (if I am understanding you correctly). I would put the user settings in their own class (or struct, if you wish) and have a property of this type on your original class:
public class UserSettings
{
string FirstName { get; set; }
string LastName { get; set; }
// etc.
}
public class MyClass
{
string MyClassProperty1 { get; set; }
// etc.
UserSettings MySettings { get; set; }
}
This way, you have named properties that you can reference instead of an arbitrary index in a list. For example, you can reference MySettings.FirstName as opposed to MySettingsList[0].
Let me know if you have any further questions.
EDIT 3:
For the question in the comments, your property would be like this:
public class MyClass
{
public List<KeyValuePair<string, string>> MySettings { get; set; }
}
EDIT 4: Based on the question's edit 2, following is how I would use this:
public class MyClass
{
// note that this type of property declaration is called an "Automatic Property" and
// it means the same thing as you had written (the private backing variable is used behind the scenes, but you don't see it)
public List<KeyValuePair<string, string> MySettings { get; set; }
}
public class MyConsumingClass
{
public void MyMethod
{
MyClass myClass = new MyClass();
myClass.MySettings = new List<KeyValuePair<string, string>>();
myClass.MySettings.Add(new KeyValuePair<string, string>("SomeKeyValue", "SomeValue"));
// etc.
}
}
You mentioned that "the property still won't appear in the object's instance," and I am not sure what you mean. Does this property not appear in IntelliSense? Are you sure that you have created an instance of MyClass (like myClass.MySettings above), or are you trying to access it like a static property (like MyClass.MySettings)?
Simple and effective alternative:
public class ClassName
{
public List<dynamic> MyProperty { get; set; }
}
or
public class ClassName
{
public List<object> MyProperty { get; set; }
}
For differences see this post: List<Object> vs List<dynamic>
public class MyClass<T>
{
private List<T> list;
public List<T> MyList { get { return list; } set { list = value; } }
}
Then you can do something like
MyClass<int> instance1 = new MyClass<int>();
List<int> integers = instance1.MyList;
MyClass<Person> instance2 = new MyClass<Person>();
IEnumerable<Person> persons = instance2.MyList;
You could do this but the T generic parameter needs to be declared at the containing class:
public class Foo<T>
{
public List<T> NewList { get; set; }
}
It's possible to have a property of type List<T> but your class needs to be passed the T too.
public class ClassName<T>
{
public List<T> MyProperty { get; set; }
}
Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.
public class MyClass<T>
{
etc

Categories