var idx = dictNames2Indexes.FirstOrDefault(x => x.Key.Contains(value)).Value;
if (idx != null)
......
I am receiving "The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?'"bool testBoolean = null;
bool testBoolean; // Default value is false
int testInteger; // Default value is 0
DateTime testDateTime; // Default value is DateTime.MinValue
bool? testBoolean; // Default value is null
int? testInteger; // Default value is null
DateTime? testDateTime; // Default value is null
dictNames2Indexes.FirstOrDefault(...criteria here...)
if (idx != null)
...then .NET is complaining and saying, "I'm either going to have a successful search and return an integer, or I'm going to have an unsuccessful search and return 0, which is an integer. So no matter what, I'm returning an int, which is not nullable." Dictionary<string, int> dictNames2Indexes = new Dictionary<string, int>()
{
{ "TEST", 1 }
};
if(dictNames2Indexes.ContainsKey("TEST"))
{
int idx = dictNames2Indexes["TEST"];
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace EE_Q29126855
{
class Program
{
static readonly Dictionary<string, int> numbers = (from i in Enumerable.Range(0, 20)
select new { Key = $"Key{i}", Value = i }).ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
static void Main(string[] args)
{
int value = default(int);
Console.WriteLine($"Default integer is 0: {value == 0}");
foreach (var i in Enumerable.Range(15, 6))
{
if (numbers.TryGetValue($"Key{i}", out value))
{
Console.WriteLine($"Value of Key{i} is {value}");
}
else
{
Console.WriteLine($"Key{i} not found in dictionary; value is 0: {value == 0}");
}
}
Console.ReadLine();
}
}
}
Produces the following output -if (dictNames2Indexes.Any(x => x.Key.Contains(value))
{
var idx = dictNames2Indexes.FirstOrDefault(x => x.Key.Contains(value)).Value;
...
}
@Shaun - that doesn't workProbably
dictNames2Indexes.Where(x => x.Key.Contains(value)).FirstOrDefault()
Open in new window
not onOpen in new window