简体   繁体   中英

Create a Dictionary from another Dictionary and a List<T> on a matching values

I have the following function, which takes a Dictionary and a List, matches rows in each of those and returns another Dictionary based on matcing items.

Is there a better way (code and performance -wise) to achieve the same result?

    public sealed class ProdIds 
    {
             public List<ProdID> Items { get; set; }
    }
    
    public sealed class ProdID
    {
            public string SpecialId { get; set; }
            public int ItemId { get; set; }
    }
    

Simplified view of the entries:

names: {100, "Name1"}, {333, "Name3"}, {212, "Name55"}, {99, "NameABC"}, ...
ids:  {"SP44", 212}, {"SP33", 333}, {"SP11", 100}, {"SP9", 99}, ...
    
    
private static Dictionary<string, string> CreateMatchedDictionary (IReadOnlyDictionary<int, string> names, List<ProdIds> ids)
{
    var dic = new Dictionary<string, string>();
    foreach (var name in names)
    {
        foreach (var id in ids)
        {
            if (name.Key == id.Items[0].ItemId)
            {
                dic.Add(id.Items[0].SpecialId, name.Value);
            }
        }
    }
    return dic;
}

What I want to be returned here, is a new Dictionary which would look similar to this:

dic: {"SP44", "Name55"}, {"SP33", "Name3"}, {"SP11", "Name1"}, {"SP9", "NameABC"}, ...

The main performance problem is that you're looping through the names dictionary instead of taking advantage of the built-in O(1) lookup:

private static Dictionary<string, string> CreateMatchedDictionary (IReadOnlyDictionary<int, string> names, List<ProdIds> ids)
{
    var dic = new Dictionary<string, string>();
    foreach (var id in ids)
    {
        string name = null;
        if (names.TryGetValue(id.Items[0].ItemId, out name)
        {
            dic.Add(id.Items[0].SpecialId, name);
        }
    }
    return dic;
}

You could use Linq to make the code more concise, but it's not going to improve performance and might make debugging harder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM