Linq Select Certain Properties Into Another Object?

后端 未结 5 676
情书的邮戳
情书的邮戳 2020-12-09 02:24

So say I have a collection of Bloops

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


        
相关标签:
5条回答
  • 2020-12-09 03:09

    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.

    0 讨论(0)
  • 2020-12-09 03:09
    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-09 03:09

    Transforming from one type into another can be accomplished by using Enumerable.Select

    In fact, there is a sample from 101 linq samples that shows a query transforming ints into strings.

    0 讨论(0)
  • 2020-12-09 03:13
    List<Bloop> myBloops = new List<Bloops>;
    //populate myRazzies
    List<Razzie> myRazzies = myBloops.Select(x => new Razzie() { FirstName = x.FirstName, LastName = x.LastName}).ToList();
    
    0 讨论(0)
  • 2020-12-09 03:15
            C# Sample - Thanks to earlier posters.
    
            List<clsObj> myList = new List<clsObj>();
            clsObj clsObjInstance = null;
            for (int i = 0; i < 10; i++)
            {
                clsObjInstance = new clsObj() { x = (i+1) % 3, a = "A" + i.ToString() };
                myList.Add(clsObjInstance);
            }
    
            List<int> extIntList = myList.Select(u => u.x).ToList();
            foreach (int u in extIntList)
                Console.Write(u.ToString() + "\t");
    
            List<string> extStringList = myList.Select(u => u.a).ToList();
            foreach (string u in extStringList)
                Console.Write(u + "\t");
    
    0 讨论(0)
提交回复
热议问题