Linq方法返回不满足条件

时间:2016-05-17 15:00:58

标签: linq conditional-statements where

我正在调用List上的Where方法,并返回不满足我条件的元素。

这是我对Where方法的调用:

IEnumerable<MyObject> list = returnList.Where(p => p.MaxDate != null && p.MinDate != null);

我期待着&#34; list&#34; IEnumerable只有同时定义了MaxDate和MinDate的对象(非空)!

&#34; list&#34;结尾与我的returnList结果相同,实际上没有&#34; list&#34;由于MaxDate和MinDate的定义(不同于null),我的where条件应该在这种情况下不返回任何元素,我是对的吗?

非常感谢您提前

EDIT2(我添加了我正在使用的命名空间,也许这有一些错误):

简单示例:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        class MyObject
        {
            public DateTime? MinDate { get; set; }
            public DateTime? MaxDate { get; set; }
            public string Description{ get; set; }

        }


        static void Main(string[] args)
        {
            List<MyObject> lista = new List<MyObject>();
            lista.Add(new MyObject { Description = "123" });
            lista.Add(new MyObject { Description = "456" });
            lista.Add(new MyObject { Description = "678" });

            IEnumerable<MyObject> returnn = lista.Where(p => p.MinDate != null && p.MaxDate != null); //this list contains 3 elements and should have 0!! Microsoft bug???? I can't understand this!
        }
}

2 个答案:

答案 0 :(得分:1)

returnList.Where(p => p.MaxDate.HasValue && p.MinDate.HasValue);

工作示例: https://dotnetfiddle.net/qQrjkC

编辑:即使!= null也应该有效,你应该在给予downvotes之前正确地进行测试

答案 1 :(得分:1)

耶稣,我现在感觉很愚蠢,我在IEnumerable属性“returnn”中查看字段“source”,而不是检查实际的ResultsView,我做了一个ToList()并且没有返回任何元素!

我很抱歉大声笑,也许有人可以关闭这个问题...

谢谢大家的努力!问题发生在电脑前(我)LOL