我有以下课程:
class customer{
public string name {get;set;}
public attributes MyAttr {get;set;}
}
class attributes
{
public string attr1 {get;set;}
public string attr2 {get;set;}
public string attr3 {get;set;}
}
所以我有客户列表,我想获得一个名称和属性列表以绑定到Gridview?
答案 0 :(得分:0)
如果您有客户列表然后遍历它,您将获得名称和属性。
foreach(customer customer in Customers)
{
String name = customer.name;
String attr1 = customer.MyAttr.attr1
String attr2 = customer.MyAttr.attr2
String attr3 = customer.MyAttr.attr3
}
对于简单循环,不需要LINQ。
答案 1 :(得分:0)
...
var nameAndAttr = listCustomers
.Select(c =>
new
{
Name = c.name,
Attributes = new[] {c.MyAttr.attr1, c.MyAttr.attr2, c.MyAttr.attr3}
});
...
答案 2 :(得分:0)
您可以将attributes
类重构为可枚举:
class attributes : IEnumerable<string>
{
public string attr1 {get;set;}
public string attr2 {get;set;}
public string attr3 {get;set;}
public IEnumerator<string> GetEnumerator()
{
return new List<string> { attr1, attr2, attr3 }.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
然后你可以使用常规的linq查询:
var attrs = myCustomer.Attributes.Where(attr => attr.StartsWith("foo"));
绑定看起来像这样:
myGridView.DataSource = myCustomer.Attributes;
如果您无法修改attributes
课程,可以为其编写扩展方法:
static class attributesExtensions
{
public static IEnumerable<string> Enumerate(this attributes attributes)
{
yield return attributes.attr1;
yield return attributes.attr2;
yield return attributes.attr3;
}
}
并使用这样的linq:
var attrs = myCustomer.Attributes.Enumerate().Where(attr => attr.StartsWith("foo"));
绑定看起来像这样:
myGridView.DataSource = myCustomer.Attributes.Enumerate();
答案 3 :(得分:0)
如果要在GridView中绑定客户名称属性,请尝试这样的操作。
List<customer> lstCustomers = new List<customer>();
lstCustomers.Add(new customer
{
name = "Name",
MyAttr = new attributes
{
attr1 = "attr1", attr2 = "attr2", attr3 = "attr3"
}
});
var result = lstCustomers
.Select(x => new
{
x.name, x.MyAttr.attr1, x.MyAttr.attr2, x.MyAttr.attr3
});
GridView2.DataSource = result;
GridView2.DataBind();