开发者

LINQ query code for complex merging of data

开发者 https://www.devze.com 2022-12-23 16:16 出处:网络
I\'ve posted this before, but I worded it poorly. I\'m trying again with a more well thought out structure.

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
{
    stati开发者_如何学编程c 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);
        }
    }
}


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号