Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading