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
}
}
});
}
}
}
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
}
}
});
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With