C#

Working with Lists

Suppose you have a List that you want to make another List from? This could be useful for an API when serializing Json from an object prior to sending it to a mobile app.

public class ListExample
{
    public static List GetAuthorSelect()
    {
        List authorSelect = new List();
        List author = new Data.AccessLayer.GetAuthors();
        {
            //create and copy the items we want to into a light list
            authorSelect = author.ConvertAll(x => new AuthorSelect
            {
                Id = x.Id,
                Name = x.Name
            });
        }
        return authorSelect;
    }

    //this method shows the equivalent using the traditional for loop
    public static List GetAuthorSelectLoop()
    {
        List authorSelect = new List();
        List author = new Data.AccessLayer.GetAuthors();
        if (author != null)
        {
            for (int i = 0; i < author.Count; i++)
            {
                authorSelect.Add(new AuthorSelect()
                {
                    Id = author[i].Id,
                    Name = author[i].Name
                });
            }
        }
        return authorSelect;
    }
}

public class AuthorSelect
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Author
{
    public int Id { get; set; }
    public string Slug { get; set; }
    public string Name { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Nickname { get; set; }
    public string Url { get; set; }
    public string Description { get; set; }
}

List.ConvertAll Method

comments powered by Disqus