Home > Blockchain >  Is there a simpler way to populate a List<UserType> using Linq?
Is there a simpler way to populate a List<UserType> using Linq?

Time:11-20

I have the following code to eventually populate a List<> in C#, though I am having to utilise a var and also a temporary var to get there, is there a single line of code to do this without the intermediary?

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 });
                }
            }
        }

Any pointers in the right direction would be appreciated

The above code works, though I know there must be an more direct method.

CodePudding user response:

Why don't you create the FullList directly?

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