简体   繁体   中英

Contains in Dictionary in C#

I have to ensure that only certain cells are there in excel and not more or less than that. Even these header cell texts are pre-specified. Even different cell text also cannot be allowed in the application.

Then based on the headers, I have to put the data into a list.

What I am doing to convert my excel in dictionary is this :

var ws = excel.Workbook.Worksheets["Sheet1"];

int headerCol = 2;

Dictionary<string, int> map = Enumerable
    .Range(ws.Dimension.Start.Column, 24 - ws.Dimension.Start.Column + 1)
    .ToDictionary(col => ws.Cells[headerCol, col].Value.ToString().Trim(), col => col);

for (int rw = 3; rw <= ws.Dimension.End.Row; rw++)
{
    if (!ws.Cells[rw, 1, rw, 24].All(c => c.Value == null))
    {
        lgl.GroupMembershipUploadInputList.Add(new GroupMembershipUploadInput()
        {
            cnst_mstr_id = (ws.Cells[rw, map["Master Id"]].Value ?? (Object)"").ToString(),
            cnst_prefix_nm = (ws.Cells[rw, map["Prefix"]].Value ?? (Object)"").ToString(),

But now how would I make sure the dictionary map only contains these much specified string keys and not anything different than that, eg Master Id and Prefix - only these 2 and exactly these two.

In actuality there are 24 keys. Is there any shorthand code to check?

The Dictionary class contains a method called ContainsKey() that can be used to check for the existance of a key within the dictionary :

if(map.ContainsKey(key))
{
      // Do something
}

If you needed to check for the existence of multiple keys, you could store the keys that you needed to check for within a collection and then use a bit of LINQ to evaluate it :

// Keys to check for
var keys = new []{ "Master_Id", "Prefix" };
// Check if all of these keys exist
if(map.Keys.All(k => keys.Contains(k)) && map.Keys.Count() == keys.Count())
{
      // All of the keys are present in your collection
}

Alternatively, you could just check the intersection of the keys via the Intersect() method and ensure they match as well :

if(map.Keys.Intersect(keys).Count() == keys.Count())
{
       // Exactly every key is present
}

Basically you want the two key sets to be equal, so you need two checks that they contain each other.

string[] keys = new[] { "Master Id", "Prefix" };
Dictionary<string, int> map = new Dictionary<string, int>();

bool check = keys.All(map.ContainsKey) && map.Keys.All(keys.Contains);

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