Set a List item in a class to a new list item and add to it in a LINQ query

Karl 1 Reputation point
2021-07-26T17:33:49.637+00:00

So lets say I have a class object called SomeObject, and one called NamesObject

    public class NamesObject 
    {
      public string FirstName {get; set;}
      public string LastName {get; set;}
    }

    public class SomeObject
    {
      public List<NamesObject> Names {get; set;}
    }

 

Then I do a LINQ query that ends with a select of a new SomeObject, I want to do something like this, but I can't work it out, or even if you can do it?

var N = (from x in sometable
select new SomeObject {
 Names = new List<NamesObject>().Add(new NamesObject { x.FirstName, x.LastName })
});
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-07-26T17:45:32.893+00:00

    Try something like this:

    var N = new SomeObject { Names = (from x in sometable select new NamesObject { FirstName = x.FirstName, LastName = x.LastName }).ToList() };

    2 people found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.