简体   繁体   English

查询没有返回值的列表

[英]Query a list where no values are returned

IEnumerable<ATable> stuff = 
        _aTableRepository.Entity.ByTitle(TITLE).ByDocTypeCode(Id).ToList();

The above returns a list of items 上面的返回项列表

decimal? xyz = stuff.Where(x => x.CLAUSE == "test").FirstOrDefault().Id ?? 0;

Now I want to query the list and get the id, which is a decimal type. 现在,我想查询列表并获取ID(十进制类型)。 However, there are no clauses that equal "test" and this line bombs out. 但是,没有子句等于“ test”,这行炸弹了。 It seems like if nothing is found, that the nullable decimal would get set to 0. 好像什么也没找到,可为空的十进制将被设置为0。

The problem with your query, is that FirstOrDefault will return default entity value if there is no matching entities. 您的查询的问题是,如果没有匹配的实体,则FirstOrDefault将返回默认实体值。 I believe entity is a reference type in your application, so you have null as default value. 我相信实体是您应用程序中的引用类型,因此您将null作为默认值。 Trying to get Id of null gives you NullReferenceException . 尝试获取null Id会给您NullReferenceException

Project sequence of entities to sequence of ids and select first one or use default value: 将实体序列投影为ID序列,然后选择第一个或使用默认值:

decimal? xyz = stuff.Where(x => x.CLAUSE == "test")
                    .Select(x => x.Id).FirstOrDefault() ?? 0;

You can also use DefaultIfEmpty to provide default value: 您还可以使用DefaultIfEmpty提供默认值:

decimal? xyz = stuff.Where(x => x.CLAUSE == "test")
                    .Select(x => x.Id)
                    .DefaultIfEmpty(0).First();

And old school approach - simply get first matching entity and check if its not null: 和老派的方法-只需获取第一个匹配的实体并检查其是否不为null:

var testEntity = stuff.FirstOrDefault(x => x.CLAUSE == "test");
decimal? xyz = testEntity == null ? 0 : testEntity.Id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM