我有以下代码最终在 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 });
}
}
}
任何正确方向的指示将不胜感激
上面的代码是有效的,尽管我知道一定有更直接的方法。
为什么不直接创建
FullList
?
List<IdStringPair> FullList = _context.Categories
.OrderBy(x => x.Category)
.Select(x => new IdStringPair{ Id = (Guid) x.Id, Text = x.Category })
.ToList();