Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
var fields = new Dictionary<string, string="">
{
{"2", "34"},
{"3", "45"},
{"4", "56"}
};


string[] listArray = { "2", "5", "6" };
List<string> list = new List<string>(listArray);

var listKey = fields.Keys.ToList();


var d1Keys = listKey.Except(list);


d1Keys will have value 3 & 4 now I want to to get the corrosponding value from dictionary fields. is there any easier way to implement this

What I have tried:

tried multple option for try get value but its only returning one value not able to pass complete list and get output in list
Posted
Updated 1-Nov-21 1:48am
Comments
[no name] 1-Nov-21 10:28am    
Like this var itmesByKeyList= d1Keys.Where(k => fields.ContainsKey(k)).Select(k => fields[k]);
Richard MacCutchan 1-Nov-21 12:47pm    
Thanks, I used your suggestion to improve my answer below.
[no name] 1-Nov-21 12:52pm    
And finally your solution is much better ;)
Richard MacCutchan 1-Nov-21 13:08pm    
Only because I copied yours. My LINQ skills are not very good.

1 solution

Try this:
C#
var listKey = fields.Keys.ToList();
var d1Keys = listKey.Except(list);
foreach (var item in d1Keys) // for all keys not in the exclusion list
{
    Console.WriteLine($"Key: {item}, Value: {fields[item]}"); // print the value of the key
}


Looking at the LINQ provided by Member 15415060 above, a neater solution would be something more like:
C#
var fields = new Dictionary<string, string>
{
{"2", "34"},
{"3", "45"},
{"4", "56"}
};
string[] listArray = { "2", "5", "6" };

var listKeys = fields.Keys.ToList().Except(listArray);
var values = listKeys.Select(k => fields[k]);
foreach (var item in values)
{
    Console.WriteLine($"item: {item}");
}
 
Share this answer
 
v4
Comments
Amit Patel1985 1-Nov-21 10:06am    
but this require a looping I am wondering is it possible without loop.
Richard MacCutchan 1-Nov-21 11:16am    
Well it depends what actual results you want.
PIEBALDconsult 1-Nov-21 11:28am    
Of course it loops, it has to loop, either you write the loop yourself (which gives you control) or depend on the loops of others (which may hide all sorts of bad stuff).
[no name] 1-Nov-21 13:09pm    
You are right it loops either way, also with e.g. LINQ. But I prefer LINQ because it is already tested thousand of times .
PIEBALDconsult 1-Nov-21 13:11pm    
But it is less efficient in many cases. Don't use Linq.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900