Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to return a new object with a selection from the list

Tags:

c#

linq

I have the following object structure:

public class A
{
    public string ID { get; set; }
    public IList<B> Values { get; set; }
}

public class B
{
    public string Code { get; set; }
    public string DisplayName { get; set; }
}

public List<A> IDs;

I would like to use Linq to query B and return a single instance of A with the single element of B in values. Is that possible? I currently do this with a foreach but I am thinking Linq would be neater.

foreach (A a in IDs)
{
    foreach (B b in a.Values)
    {
        if (b.Code == code)
        {
            return (new A()
            {
                ID = a.ID,
                Values = new List<B>()
                {
                    new B()
                    {
                        Code = b.Code,
                        DisplayName = b.DisplayName
                     }
                 }
            });
        }
    }
}
like image 927
flip Avatar asked Dec 20 '22 02:12

flip


2 Answers

Try this:

IDs.Where(a=>a.ID = id)
   .Select(a => new A() 
   {
       ID = a.ID,
       Values = new List<B>()
       {
           new B() 
           { 
               Code = a.Values.First().Code, 
               DisplayName = a.Values.First().DisplayName 
           }
       }
    });
like image 154
Abhishek Jain Avatar answered Dec 22 '22 15:12

Abhishek Jain


In LINQ with the query-syntax:

return (from a in IDs
        from b in a.Values
        where b.Code == code
        select (new A
        {
            ID = a.ID, Values = new List<B>
            {
                new B
                {
                    Code = b.Code, 
                    DisplayName = b.DisplayName
                }
            }
        })).FirstOrDefault();
like image 31
Cédric Bignon Avatar answered Dec 22 '22 15:12

Cédric Bignon