'Get variable list from a list (using Linq ?)

Is there any way of reducing this getter to about one line using something like linq? I did a search and didn't find anything. Just curious.

private List<UserItem> userItems
{ 
    get 
    { 
        List<UserItem> list = new List<UserItem>();

        foreach (var item in items) {
            list.Add(item.UserItem);
        }

        return list;
    }
}


Solution 1:[1]

Simply:

get {
    return items.Select(x => x.UserItem).ToList();
}

MSDN Link for Select: http://msdn.microsoft.com/en-us/library/bb548891(v=vs.110).aspx

Basically, it projects what you want into a new list. In the above example, we are projecting each UserItem property of the objects in your items collection into a list.

EDIT:

8 years later... its possible to simplify it further now that properties can be expression bodies.

private List<UserItem> UserItems => items.Select(x => x.UserItem).Tolist();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1