我怎么看待像LINQ空列表空列表? [英] how do I treat null lists like empty lists in linq?

查看:87
本文介绍了我怎么看待像LINQ空列表空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些linqpad测试code。当这个运行时,它错误,因为项目的第二个实例有子项的空列表,而不是一个空的列表。

Below is some linqpad test code. When this runs it errors because the second instance of "item" has a null list of subitems as opposed to an empty list.

我要治疗这两种情况下(null或空列表)以完全相同的方式,但我想知道是否有比只是把一个空检查的名单上,初始化一个空表时,有一个空一个更清洁的方式。

I want to treat both situations (null or empty list) in exactly the same way but I wondered if there was a cleaner way than just putting a null check on the list and initialising an empty list when there's a null.

换句话说,我可以做到这一点:

in other words, I could do this:

from si in (i.subitems == null ? new List<item>() : i.subitems)

不过,这是一个有点丑陋,我不知道我怎么会提高呢?

but that's a little ugly and I wondered how I could improve on that?

public class item
{
    public string itemname { get; set; }
    public List<item> subitems { get; set; }
}

void Main()
{
    List<item> myItemList = new List<item>() 
    {
        new item 
        {
            itemname = "item1",
            subitems = new List<item>()
            {
                new item { itemname = "subitem1" },
                new item { itemname = "subitem2" }
            }
        },
        new item 
        {
            itemname = "item2"
        }
    };

    myItemList.Dump();

    var res = (from i in myItemList
            from si in i.subitems
            select new {i.itemname, subitemname = si.itemname}).ToList();

    res.Dump();
}

作为奖金的问题,可同样的LINQ查询重新psented作为一个lambda $ P $和处理空值以同样的方式?

as a bonus question, can this same linq query be represented as a lambda and treat nulls the same way?

干杯,克里斯

推荐答案

您可以使用空合并运算符

var res = (from i in myItemList
           from si in i.subitems ?? new List<item>()
           select new { i.itemname, subitemname = si.itemname }).ToList();

但我认为你应该只筛选空的了

But I think you should just filter the empty ones out

var res = (from i in myItemList
           where i.subitems != null
           from si in i.subitems
           select new { i.itemname, subitemname = si.itemname }).ToList();

作为一个lambda版本,你可以说

As for a lambda version you could say

var res = myItemList.Where(x => x.subitems != null)
                    .SelectMany(
                        x => x.subitems.Select(
                            y => new { x.itemname, subitemname = y.itemname }
                        )
                     );

但查询语法版方式更加r​​eadble。

But the query syntax version is way more readble.

这篇关于我怎么看待像LINQ空列表空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆