views:

37

answers:

1

I've posted this before, but I worded it poorly. I'm trying again with a more well thought out structure.

I have the following code and I am trying to figure out the shorter linq expression to do it 'inline'. Please examine the "Run()" method near the bottom. I am attempting to understand how to join two dictionaries together based on a matching identifier in one of the objects - so that I can use the query in this sort of syntax.

 var selected = from a in items.List()
                // etc. etc.
                select a;

so that I can define my structure in code like ...

TModelViewModel = new TModelViewModel
{
 TDictionary = from a in items... etc. etc... 
}

instead of going through a bunch of foreach loops, extra object declarations, etc.


This is my class structure. The Run() method is what I am trying to simplify. I basically need to do this conversion inline in a couple of places, and I wanted to simplify it a great deal so that I can define it more 'cleanly'.

class TModel
{
    public Guid Id { get; set; }
}
class TModels : List<TModel>
{
}
class TValue
{
}

class TStorage
{
    public Dictionary<Guid, TValue> Items { get; set; }
}

class TArranged
{
    public Dictionary<TModel, TValue> Items { get; set; }
}
static class Repository
{
    static public TItem Single<TItem, TCollection>(Predicate<TItem> expression)
    {
        return default(TItem); // access logic.
    }
}

class Sample
{
    public void Run()
    {
        TStorage tStorage = new TStorage();
        // access tStorage logic here.

        Dictionary<TModel, TValue> d = new Dictionary<TModel, TValue>();

        foreach (KeyValuePair<Guid, TValue> kv in tStorage.Items)
        {
            d.Add(Repository.Single<TModel, TModels>(m => m.Id == kv.Key),kv.Value);
        }
    }
}
+1  A: 

Haven't really tested this, and it's quite ugly, but I think this should work:

        Dictionary<TModel, TValue> d = new Dictionary<TModel, TValue>();

        d = d.Concat(tStorage
            .Items
            .Select(i => new KeyValuePair<TModel, TValue>(
                new TModel { Id = i.Key }, i.Value))).ToDictionary(i => i.Key, i => i.Value);
BFree
Hrnm. I don't see anywhere where it is accessing the repository of TModel items, though.
Stacey
Aha, found it. On the third line, where Id = i.Key. I would set that to a Predicate<TModel> expression identifying the match in the repository. This code works perfectly, thank you very much! Can I bother you to explain a bit what is going on? I'm not sure why it works.
Stacey