【发布时间】:2022-11-20 19:40:47
【问题描述】:
我有以下代码最终在 C# 中填充 List<>,尽管我必须使用一个 var 和一个临时 var 才能到达那里,是否有一行代码可以在没有中介的情况下执行此操作?
public class IdStringPair
{
public Guid Id { get; set; }
public string Text { get; set; }
}
public void CreateList()
{
List<IdStringPair> FullList = new List<IdStringPair>();
using dBContext _context = GetTempContext();
{
var tempList = _context.Categories.Select(x => new { x.Id, x.Category }).OrderBy(o => o.Category).ToList();
foreach (var item in tempList)
{
FullList.Add(new IdStringPair { Id = (Guid)item.Id, Text = item.Category });
}
}
}
任何正确方向的指示将不胜感激
上面的代码有效,但我知道必须有更直接的方法。
【问题讨论】:
-
IdStringPair = _context.Categories.Select(x => new IdStringPair { Id = x.Id, Text = x.Category }).OrderBy(o => o.Text).ToList()? -
或
FullList.AddRange(_context.Categories.Select(x => new IdStringPair { Id = x.Id, Text = x.Category }).OrderBy(o => o.Text)); -
是的,这就是我一直在寻找的!谢谢
-
我认为使用这段代码,排序将在内存中完成?我是对的?