.ToString().ToList() 返回一个新列表<char>



所以我有一个查询,搜索各种项目。但是我只想要它们的Id,所以我使用投影只返回Id,而不返回项目的其他元素。但从ObjectId转换为.ToString(),然后.ToList()返回List<char>而不是List<string>

var items = await this.ItemAppService.GetAllAsync(expression,
x => new
{
Ids = x.Id.ToString().ToList(),
});
var Ids = items.SelectMany(x => x.Ids.Select(x => x)).ToList();

我想了解为什么我要返回List<Char>以及如何将其转换为List<String>

第一个ToList是不必要的,您需要字符串,并且通过调用ToList()将字符串转换为字符数组。所以代码应该重写为:

var items = await this.ItemAppService.GetAllAsync(expression,
x => new
{
Id = x.Id.ToString(),
});
var ids = items.Select(x => x.Id).ToList();

.ToString().ToList()返回一个新的List<char>

是的,因为string是一个IEnumerable<char>(一堆字符可以被枚举)。ToList是所有IEnumerable<T>的扩展方法,返回一个List<T>

所以匿名对象中的Ids属性已经是List<char>:

x => new
{
// this "Ids" is already a List<char>
Ids = x.Id.ToString().ToList(),
});

然后你对它做更多的洗牌,但没有任何有意义的改变。x.Ids.Select(x => x)返回与x.Ids内容相同的Innumerable<char>SelectMany将每个匿名对象中的所有IEnumerable<char>加起来成为一个大的IEnumerable<char>,然后将其转换为列表。

我不知道你为什么在这里使用匿名对象。如果您只想要包含所有id的List<string>,只需执行:

var ids = await this.ItemAppService.GetAllAsync(
expression,
// assuming x.Id is not already a string
x => x.Id.ToString()
).ToList();

相关内容

最新更新