Linq Select Certain Properties Into Another Object?

52,420

Solution 1

This should do the job:

Dim results = From item In bloops _
              Select New Razzie() With _
              { _
                  .FirstName = item.FirstName, _
                  .LastName = item.LastName _
              }

And if you want to convert the result from IEnumerable<Bloop> (what the LINQ query returns) to an array or List<Bloop>, just append a call to the ToArray() or ToList() extension methods respectively.

Edit: Corrected the code so that it now has valid VB.NET 9 syntax.

Solution 2

List<Bloop> myBloops = new List<Bloops>;
//populate myRazzies
List<Razzie> myRazzies = myBloops.Select(x => new Razzie() { FirstName = x.FirstName, LastName = x.LastName}).ToList();

Solution 3

public void Linq9()
{
    string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };

    var upperLowerWords =
        from w in words
        select new { Upper = w.ToUpper(), Lower = w.ToLower() };

    foreach (var ul in upperLowerWords)
    {
        Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
    }
}
Share:
52,420
Russ Bradberry
Author by

Russ Bradberry

I am the CTO at SimpleReach, the leading content data platform. I am responsible for designing and building out highly scalable, high volume, distributed data solutions. Prior to SimpleReach I built out an SSP that included automated ad-network optimization and inventory forecasting. Additionally, I managed the engineering efforts for one of San Diego's foremost web design firms and an employment and training organization that focuses its efforts on placing Veterans in positions that highlight their capabilities. I am a US Navy Veteran, a DataStax MVP for Apache Cassandra, and co-author of "Practical Cassandra" A developer's guide to Apache Cassandra

Updated on May 20, 2020

Comments

  • Russ Bradberry
    Russ Bradberry almost 4 years

    So say I have a collection of Bloops

    Class Bloop
      Public FirstName
      Public LastName
      Public Address
      Public Number
      Public OtherStuff
    End Class
    

    Then I have a class of Razzies

    Class Razzie
      Public FirstName
      Public LastName
    End Class
    

    Is it possible using Linq to select the FirstName and LastName out of all the Bloops in the collection of Bloops and return a collection of Razzies? Or am i limited to a For-Loop to do my work?

    To clear up any confusion, either VB or C# will do. Also this will probably lead to me asking the question of (What about using a "Where" clause).