我有以下代碼最終在 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 });
}
}
}
任何正確方向的指示將不勝感激
上面的代碼有效,但我知道必須有更直接的方法。
uj5u.com熱心網友回復:
你為什么不FullList直接創建?
List<IdStringPair> FullList = _context.Categories
.OrderBy(x => x.Category)
.Select(x => new IdStringPair{ Id = (Guid) x.Id, Text = x.Category })
.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/536504.html
