Resolved check if list contains item from another list

ram_rocks

Active member
Joined
Jun 14, 2021
Messages
27
Programming Experience
1-3
Hello All,

In below Dictionary I have a list<string> and would like to check local string within this list and if it does not contains would like to add to the list.
Can anyone please help me out with the logic in if condition

Dictionary<string, Dictionary<string, List<string>>> dictLst = new();


C#:
Dictionary<string, Dictionary<string, List<string>>> Lst = new();

if (Lst.ContainsKey(firstkey))
{
    var Elem = Lst[firstkey];
    if (Elem.ContainsKey(secondkey))
    {
        // here i would like to check the Elem.Values -> list<string> values with
        // other string, if it does not contains then add string to List<string>
    }
}
 
Solution
If I'm reading your question correctly, I would do it like this:

C#:
if (Lst.TryGetValue(firstKey, out var firstValue) &&
    firstValue.TryGetValue(secondKey, out var secondValue) &&
    !secondValue.Contains(newValue))
{
    secondValue.Add(newValue);
}
Using TryGetValue enables you to do everything in a single expression, rather than nesting if blocks. Declaring those local variables inline requires a fairly recent version of C#. If you're using an older version then you can just declare them conventionally:
C#:
Dictionary<string, List<string>> firstValue;
List<string> secondValue;

if (Lst.TryGetValue(firstKey, out firstValue) &&
    firstValue.TryGetValue(secondKey, out secondValue) &&...
If I'm reading your question correctly, I would do it like this:

C#:
if (Lst.TryGetValue(firstKey, out var firstValue) &&
    firstValue.TryGetValue(secondKey, out var secondValue) &&
    !secondValue.Contains(newValue))
{
    secondValue.Add(newValue);
}
Using TryGetValue enables you to do everything in a single expression, rather than nesting if blocks. Declaring those local variables inline requires a fairly recent version of C#. If you're using an older version then you can just declare them conventionally:
C#:
Dictionary<string, List<string>> firstValue;
List<string> secondValue;

if (Lst.TryGetValue(firstKey, out firstValue) &&
    firstValue.TryGetValue(secondKey, out secondValue) &&
    !secondValue.Contains(newValue))
{
    secondValue.Add(newValue);
}
Also, if all the items in the inner lists are going to be unique, you might consider using a HashSet<string> instead. It does lack some of the features of the List<T> but it ensures uniqueness and, therefore, doesn't require explicit checking when adding a new item. The Add method simply returns false if the item already exists:
C#:
Dictionary<string, Dictionary<string, HashSet<string>>> Lst = new();

if (Lst.TryGetValue(firstKey, out var firstValue) &&
    firstValue.TryGetValue(secondKey, out var secondValue))
{
    secondValue.Add(newValue);
}
 
Solution
Back
Top Bottom