Reputation: 73
I have classes Item
and Product
public class Item
{
public int Id;
public string Name;
public Product[] product{ get; set; }
}
public class Product
{
public int Id;
public string productname;
}
I got these details as List<Item> lstItem = new List<Item>();
.My challenge is I want to get productname
from this list with condition id
is not zero.So I try with linq but I cannot get result. please help on this.
Upvotes: 1
Views: 1207
Reputation: 37299
Use SelectMany
to flatten the inner collections and then filter them
var result = lstItem.SelectMany(item => item.product)
.Where(product => product.Id != 0)
.Select(product => product.productname);
Or in query syntax:
var result = from item in lstItem
from product in item.Product
where product.Id != 0
select product.productname;
The result
is an IEnumerable<string>
. To get a single string
containing all the values:
string concatenatedProductNames = string.Join(", ", result);
Also I'd recommend changing your classes to match the C# naming conventions:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public Product[] Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
}
Upvotes: 2