如何在linq中连接两个表列名并产生一个结果

本文关键字:结果 一个 连接 两个 linq | 更新日期: 2023-09-27 18:05:46

需要清除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

如何实现。。?

如何在linq中连接两个表列名并产生一个结果

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();
}

我刚刚使用了这个查询,并完美地获得了值。。

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();