Skip to main content
 首页 » 编程设计

c#之如何从表记录中选择除某些列外的记录

2024年02月06日13Free-Thinker

我有一个实体数据库,是从 sql 数据库创建的。我需要在 datagridview 上显示记录,我正在使用这段代码。

DBEntities db = new DBEntities(); 
dataGridView1.DataSource = db.Agent.Select(x => new { Name = x.Name, Second_Name = x.Second_Name}).ToList(); 

例如,真实代理表包含大约 10 列,我需要显示所有列,除了“id”。如果我每 8 列都做同样的事情,就会变成一长串毫无意义的行。如何做得更健忘和更好。

请您参考如下方法:

如果你不想使用匿名类型来指定你想要的字段,你可以:

  1. 接受结果集中的 ID,或者
  2. 包括 Select 中除 ID 之外的所有列,或者
  3. 使用映射库,例如 AutoMapper。

Linq 中没有Select Except 语句。但是,您可以使用此扩展方法来完成同样的事情:

/// <summary> 
/// Returns all fields/properties from <paramref name="source"/> except for the field(s)/property(ies) listed in the selector expression. 
/// </summary> 
public static IQueryable SelectExcept<TSource, TResult>( this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector ) 
{ 
    var newExpression = selector.Body as NewExpression; 
 
    var excludeProperties = newExpression != null 
            ? newExpression.Members.Select( m => m.Name ) 
            : new[] { ( (MemberExpression)selector.Body ).Member.Name }; 
 
    var sourceType = typeof( TSource ); 
    var allowedSelectTypes = new Type[] { typeof( string ), typeof( ValueType ) }; 
    var sourceProperties = sourceType.GetProperties( BindingFlags.Public | BindingFlags.Instance ).Where( p => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (PropertyInfo)p ).PropertyType ) ) ).Select( p => ( (MemberInfo)p ).Name ); 
    var sourceFields = sourceType.GetFields( BindingFlags.Public | BindingFlags.Instance ).Where( f => allowedSelectTypes.Any( t => t.IsAssignableFrom( ( (FieldInfo)f ).FieldType ) ) ).Select( f => ( (MemberInfo)f ).Name ); 
 
    var selectFields = sourceProperties.Concat( sourceFields ).Where( p => !excludeProperties.Contains( p ) ).ToArray(); 
 
    var dynamicSelect =  
            string.Format( "new( {0} )", 
                    string.Join( ", ", selectFields ) ); 
 
    return selectFields.Count() > 0 
        ? source.Select( dynamicSelect ) 
        : Enumerable.Empty<TSource>().AsQueryable<TSource>(); 
} 

延伸阅读
Use SelectExcept When You Are Too Lazy to Type