user13210765
user13210765

Reputation:

Multiple elements in .Select()

It's probably easy thing but for some reason i'm unable to find solution.

Lets say i have collection of specific type, best example - Person. And i want to take only FirstName, LastName, and Age, and ignore the rest.

So far i have tried:

var list2 = list1.Select(x => { x.FirstName; x.LastName; x.Age });
var list2 = list1.Select(x => new { x.FirstName, x.LastName, x.Age });

But it won't even compile.

Upvotes: 0

Views: 62

Answers (2)

Blindy
Blindy

Reputation: 67362

Your second example works fine:

    cs.Select(x => new { x.FirstName, x.LastName, x.Age });

An even better way is to use a value tuple, they use less memory and are much easier to garbage collect (fewer roots):

    cs.Select(x => (x.FirstName, x.LastName, x.Age));

Online reference

Upvotes: 1

StepTNT
StepTNT

Reputation: 3967

Based on your comments, seems like you want to strip some properties from your Person objects, by selecting just a few of them.

This is one way you can do it:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    // This property will be stripped
    public string OtherProperty { get; set; }

    public override string ToString()
    {
        return $"{nameof(FirstName)}: {FirstName}, {nameof(LastName)}: {LastName}, {nameof(Age)}: {Age}, {nameof(OtherProperty)}: {OtherProperty}";
    }
}

internal class Program
{
    static IEnumerable<Person> StrippedPersons(IEnumerable<Person> source)
    {
        // Selects only some of the properties that you want to return
        return source.Select(x => new Person
        {
            FirstName = x.FirstName, 
            LastName = x.LastName, 
            Age = x.Age
        });
    }

    private static void Main(string[] args)
    {
        var list1 = new List<Person>()
        {
            new Person
            {
                Age = 10,
                FirstName = "First",
                LastName = "Last",
                OtherProperty = "THIS WILL BE DISCARDED"
            }
        };

        Console.WriteLine(string.Join("\n", list1));

        var list2 = StrippedPerson(list1).ToList();

        Console.WriteLine(string.Join("\n", list2));
    }
}

Output is:

FirstName: First, LastName: Last, Age: 10, OtherProperty: THIS WILL BE DISCARDED

FirstName: First, LastName: Last, Age: 10, OtherProperty:

If you want this to be somehow dynamic, in the sense that you want to pass the name of the needed properties as a parameter to your method instead of having them hardcoded, we may need to use reflection and it's better to edit your question.

Upvotes: 0

Related Questions