需要在linq上清除一个疑问
public List<SelectListItem> GetAttributeName()
{
var attri = (from z in _entities.Attributes
select z).AsEnumerable()
.Select(z => new SelectListItem {
Text = z.AttributeName + " (" + z.AttributeType.AttributeTypeCode + ")",
Value = z.AttributeID.ToString()
});
return attri.ToList();
}
在这一行
Text = z.AttributeName + " (" + z.AttributeType.AttributeTypeCode + ")",
输出将是.. 喜欢这个..
abcd (efgh)
ijkl(mnop)
qrst(uvwx)
但我需要输出
abcd
ijkl
qrst
efgh
mnop
uvwx
如何实现......?
答案 0 :(得分:3)
public List<SelectListItem> GetAttributeName()
{
return _entities.Attributes
.Select(a => new SelectListItem {
Text = a.AttributeName,
Value = a.AttributeID.ToString() })
.Concat(_entities.Attributes.AsEnumerable()
.Select(a => new SelectListItem {
Text = a.AttributeType.AttributeTypeCode.ToString(),
Value = a.AttributeID.ToString() })
.ToList();
}
或者在对数据库的单个查询中(前一个示例将查询数据库两次):
public List<SelectListItem> GetAttributeName()
{
var attributes = _entities.Attributes
.Select(a => new {
a.AttributeName,
a.AttributeType.AttributeTypeCode,
a.AttributeID
}).ToList();
return attributes.Select(a => new SelectListItem {
Text = a.AttributeName,
Value = a.AttributeID.ToString() })
.Concat(attributes.Select(a => new SelectListItem {
Text = a.AttributeTypeCode.ToString(),
Value = a.AttributeID.ToString() })
.ToList();
}
答案 1 :(得分:0)
我刚刚使用了这个查询并完美地获得了值..
var attributes = _entities.Attributes.ToList().Select(a => new SelectListItem
{
Text = a.AttributeName,
Value = a.AttributeID.ToString()
}).Concat(_entities.AttributeTypes.ToList().Select(a => new SelectListItem
{
Text = a.AttributeTypeCode,
Value = a.AttributeTypeID.ToString()
}).Distinct().ToList());
return attributes.ToList();