App
App

Reputation: 356

Efficient and better way of looping a list and a dictionary

I have following TestDataDto.

  1. public class TestDataDto
    {
       public int ProgramId { get; set; }
       public string ProgramName { get; set; }
       public bool IsEnable { get; set; }
    }
    
  2. List of TestDataDto without IsEnable being set

    var testDatas = new List<TestDataDto>
        {
            new TestDataDto {ProgramId = 1, ProgramName = "Abc"},
            new TestDataDto {ProgramId = 2, ProgramName = "xyz"},
            new TestDataDto {ProgramId = 3, ProgramName = "jkl"},
        };
    
  3. Dictionary of test data specifying which program id is enable

    var enableTestData = new Dictionary<int, bool>();
        enableTestData[1] = false;
        enableTestData[2] = true;
        enableTestData[3] = true;
    

Now, I have to set IsEnable property of the items of testDatas depending on corresponding program ids in enableTestData dictionary.

I can do this like this.

   foreach (var b in enableTestData)
        {
            foreach (var testDataDto in testDatas)
            {
                if (testDataDto.ProgramId == b.Key)
                {
                    testDataDto.IsEnable = b.Value;
                }
            }
        }

But does not seem to be the efficient way or rather code does not look good :-(. Can someone please guide me what will be the best way to achive this?

Regards

Upvotes: 0

Views: 63

Answers (2)

serhiyb
serhiyb

Reputation: 4833

  testDatas.ForEach(d => d.IsEnable = enableTestData[d.ProgramId]);

or safe way:

testDatas.ForEach(d => d.IsEnable = enableTestData.ContainsKey(d.ProgramId) && enableTestData[d.ProgramId]);

Same O(n) as @MarcinJuraszek answer but maybe shorter code.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

There is a better way. Instead of iterating over entire dictionary use TryGetValue to check if value you're looking for exists:

foreach (var testDataDto in testDatas)
{
    bool value;
    testDatas.TryGetValue(testDataDto.ProgramId, out value);
    testDataDto.IsEnabled = value;
}

Because lookup in Dictionary<TKey, TValue> is an O(1) operation it changes your O(n*m) method into O(n).

Upvotes: 8

Related Questions