gpt4 book ai didi

c# - 将空元素添加到列表

转载 作者:行者123 更新时间:2023-11-30 15:00:16 24 4
gpt4 key购买 nike

我有 list :

var Filials = Db.FILIALS.AsEnumerable().Where(x => x.PREFIX > 0).Select(x => new { Name = string.Format("{0} {1}", x.PREFIX, x.NAME), FilialId = (Guid?)x.FILIALID }).OrderBy(x => x.Name).ToList();

我需要向这个列表中添加空元素。我试试这个变体:

var lst = new[] { new { Name = string.Empty, FilialId = (Guid?)null } }.ToList();
var Filials = Db.FILIALS.AsEnumerable().Where(x => x.PREFIX > 0).Select(x => new { Name = string.Format("{0} {1}", x.PREFIX, x.NAME), FilialId = (Guid?)x.FILIALID }).OrderBy(x => x.Name).ToList();
lst = lst.Union(Filials);

但是报错:

Cannot implicitly convert type System.Collection.Generic.IEnumerable to System.Collection.Generic.List

在最后一行。

向列表添加元素的正确方法是什么?

最佳答案

您需要替换 ToList()AsEnumerable()在声明 lst 的行中.

问题是 lst类型为 List<anonymous type>但是Union返回 IEnumerable<anonymous type> .一个IEnumerable<T>不能分配给 List<T> 类型的变量.

使用 AsEnumerable()使 lst IEnumerable<anonymous type> 类型的变量.

关于c# - 将空元素添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15613863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com