【问题标题】:Is there a simpler way to populate a List<UserType> using Linq?有没有更简单的方法来使用 Linq 填充 List<UserType>?
【发布时间】: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 =&gt; new IdStringPair { Id = x.Id, Text = x.Category }).OrderBy(o =&gt; o.Text).ToList()
  • FullList.AddRange(_context.Categories.Select(x =&gt; new IdStringPair { Id = x.Id, Text = x.Category }).OrderBy(o =&gt; o.Text));
  • 是的,这就是我一直在寻找的!谢谢
  • 我认为使用这段代码,排序将在内存中完成?我是对的?

标签: c# linq foreach var


【解决方案1】:

为什么不直接创建FullList

List<IdStringPair> FullList = _context.Categories
    .OrderBy(x => x.Category)
    .Select(x => new IdStringPair{ Id = (Guid) x.Id, Text = x.Category  })
    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多