如何从一些列以外的表格记录中进行选择 [英] How to Select from table records except some columns

查看:145
本文介绍了如何从一些列以外的表格记录中进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是一个例子,真正的代理表包含大约10列,我需要显示所有,exept'id 。如果我为每8列做同样的事情,就会成为一个长而无意义的行。

解决方案

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


  1. 在结果集中拥有ID,或

  2. 包含中的所有列选择除了ID,或

  3. 使用映射库,如AutoMapper。

在Linq中没有选择除语句。但是,您可以使用此扩展方法来完成相同的操作:

  ///< summary> 
///返回< paramref name =source/>中的所有字段/属性除了选择器表达式中列出的字段/属性(ies)。
///< / summary>
public static IQueryable SelectExcept< TSource,TResult>(此IQueryable< TSource>源,表达式&FunC< TSource,TResult>>选择器)
{
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)))。选择(p =>((MemberInfo)p).Name);
var sourceFields = sourceType.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(f => allowedSelectTypes.Any(t => t.IsAssignableFrom(((FieldInfo)f).FieldType)))。选择(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>();
}

进一步阅读

使用SelectExcept当您是太懒了键入


I have a entity database, created from sql database. I need to show record on datagridview, i am using this code.

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

It's example, real agent table contain around 10 columns, and i need to show all, exept 'id'. If i do same for every 8 columns, become a long and senseless row. How to do it more obliviuous and good.

解决方案

If you don't want to use an anonymous type to specify the fields you want, you can:

  1. Live with having the ID in the result set, or
  2. Include all of the columns in the Select except for the ID, or
  3. Use a mapping library, like AutoMapper.

There's no Select Except statement in Linq. However, you can use this extension method to accomplish the same thing:

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

Further Reading
Use SelectExcept When You Are Too Lazy to Type

这篇关于如何从一些列以外的表格记录中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆