views:

30

answers:

2

Hi,

I'm trying to make long codes short. The original codes does something following:

using (var context = new DataEntities())
{
context.Table1.Foreach(x =>{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});

context.Table2.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});

context.Table3.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});
// continue...
}

As you see, there is lots of similar code here. So, I thought I should refactor it though, it's pretty hard for me since I cannot cast context.Table1 to anything, for an example, to cast context.Table1 to ObjectSet<EntityObject> to implement a method which does all the same action for the tables.

I just want to put similar codes into a method, does anyone have a good idea?

Thanks in advance,
Yoo

+2  A: 

You should be able to use .Cast<SomeCommonType> to get an IEnumerable<T> of them? Assuming there is come commonality.

Otherwise; perhaps just IEnumerable? (non-generic)

Marc Gravell
Thank you for your reply. I totally forgot about that extension method, but no luck, I get NotSupportedException which says 'Linq to Entities casts only Entity Data Model type blah blah blah' (Sorry, it's Japanese so I cannot paste it directly) with the following test code:`var list = context.Table3.Cast<EntityObject>().ToList();``list.ForEach(x => Console.WriteLine(x.ToString());`
Yoo Matsuo
+2  A: 

Generics?

private void DoSomethingWithAnyTable<T>(ObjectSet<T> table) where T : EntityObject
{
    table.Foreach(x =>{ 
        // Omit ... updating UI 
        DoSomething(x); 
        // Omit ... updating UI                     
    });
}

Then

DoSomethingWithAnyTable(context.Table1);
DoSomethingWithAnyTable(context.Table2);
DoSomethingWithAnyTable(context.Table3);
Allon Guralnek
That works brilliantly. Thank you very much!
Yoo Matsuo