我有课程Item
和Product
public class Item
{
public int Id;
public string Name;
public Product[] product{ get; set; }
}
public class Product
{
public int Id;
public string productname;
}
我将这些详细信息设为List<Item> lstItem = new List<Item>();
。我的挑战是我希望从此列表中获取productname
条件id
不为零。所以我尝试使用linq但我无法获得结果。请帮忙。
答案 0 :(得分:1)
使用SelectMany
展平内部集合,然后过滤它们
var result = lstItem.SelectMany(item => item.product)
.Where(product => product.Id != 0)
.Select(product => product.productname);
或者在查询语法中:
var result = from item in lstItem
from product in item.Product
where product.Id != 0
select product.productname;
result
是IEnumerable<string>
。要获得包含所有值的单个string
:
string concatenatedProductNames = string.Join(", ", result);
另外,我建议更改您的课程以匹配https://www.dropbox.com/s/5w92uq10ao94t84/Screenshot%202016-10-26%2018.51.34.png?dl=0:
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; }
}