如何确保FirstOrDefault <keyvaluepair>返回了值</keyvaluepair>

时间:2009-08-26 15:07:40

标签: c# linq

以下是我正在尝试做的简化版本:

var days = new Dictionary<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");

var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

由于KeyValuePair变量中不存在'xyz',因此FirstOrDefault方法不会返回有效值。我希望能够检查这种情况,但我意识到我无法将结果与“null”进行比较,因为KeyValuePair是一个结构。以下代码无效:

if (day == null) {
    System.Diagnotics.Debug.Write("Couldn't find day of week");
}

我们尝试编译代码,Visual Studio会抛出以下错误:

Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'

如何检查FirstOrDefault是否返回了有效值?

4 个答案:

答案 0 :(得分:138)

FirstOrDefault不返回null,返回default(T) 你应该检查:

var defaultDay = default(KeyValuePair<int, string>);
bool b = day.Equals(defaultDay);

来自MSDN - Enumerable.FirstOrDefault<TSource>

  如果source为空,则

默认( TSource );否则, source 中的第一个元素。

注意:

答案 1 :(得分:50)

在我看来,这是最简洁明了的方式:

var matchedDays = days.Where(x => sampleText.Contains(x.Value));
if (!matchedDays.Any())
{
    // Nothing matched
}
else
{
    // Get the first match
    var day = matchedDays.First();
}

这完全绕过结构使用奇怪的默认值。

答案 2 :(得分:0)

您可以这样做:

var days = new Dictionary<int?, string>();   // replace int by int?
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");

var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

然后:

if (day.Key == null) {
    System.Diagnotics.Debug.Write("Couldn't find day of week");
}

答案 3 :(得分:0)

选择一个有效值列表,然后检查它是否包含您的 day.Value;像这样:

var days = new Dictionary<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
days.Add(7, "Sunday");
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

//check that FirstOrDefault has returned a valid value
if (days.Select(x=>x.Value).Contains(day.Value))
{
    //VALID
}
else
{
    System.Diagnostics.Debug.Write("Couldn't find day of week");
}

这是另一个使用键值对列表的示例:

var days = new List<KeyValuePair<int, string>>();
days.Add(new KeyValuePair<int, string>(1, "Monday"));
days.Add(new KeyValuePair<int, string>(1, "Tuesday"));
days.Add(new KeyValuePair<int, string>(1, "Sunday"));
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

//check that FirstOrDefault has returned a valid value
if (days.Select(x => x.Value).Contains(day.Value))
{
    //VALID
}
else
{
    System.Diagnostics.Debug.Write("Couldn't find day of week");
}

希望这对某人有所帮助!