如何在Lambda LINQ中排除属性而不是选择 [英] How to Except Property instead of Select in Lambda LINQ
本文介绍了如何在Lambda LINQ中排除属性而不是选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个获取表的代码。这是我的示例代码:
I have a code that fetching a table. Here's my sample code:
public IQueryable<MyItem> MyItems(){
return context.MyItem;
}
以下是MyItem的示例属性
Here are the sample properties of MyItem
public int Id {get;set;}
public byte[] Image {get;set;}
public string Name {get;set;}
因为, byte []
可以有多个字符,我不想在搜索中包括,因为如果我有10,000个项目之类的记录将花费很长时间。
Since, byte[]
can have multiple characters, I don't want to include then in searching because it will take so long if I have a records like 10,000 items.
通常,我会选择
,例如:
public IQueryable<MyItem> MyItems(){
return context.MyItem.Select(item=>new MyItem{
Id=item.Id,
Name=item.Name
});
}
这对少数酒店而言还可以,但我拥有10到20处酒店,将它们一一写入很麻烦。
This is okay for few properties, but what I have a 10-20 properties, it would be hassle to write them one by one.
有什么办法,只是我的lambda中的 Image
属性用于更短的代码?
Is there any way like, I just Except the property Image
in lambda for shorter code?
推荐答案
创建自己的扩展方法 SelectExcept
:
public static IQueryable<T> SelectExcept<T, TKey>(this IQueryable<T> sequence,
Expression<Func<T, TKey>> excluder)
{
List<string> excludedProperties = new List<string>();
if (excluder.Body is MemberExpression memberExpression)
{
excludedProperties.Add(memberExpression.Member.Name);
}
else if (excluder.Body is NewExpression anonymousExpression)
{
excludedProperties.AddRange(anonymousExpression.Members.Select(m => m.Name));
}
var includedProperties = typeof(T).GetProperties()
.Where(p => !excludedProperties.Contains(p.Name));
return sequence.Select(x => Selector(x, includedProperties));
}
private static T Selector<T>(T obj, IEnumerable<PropertyInfo> properties)
{
var instance = Activator.CreateInstance<T>();
foreach (var property in properties)
property.SetValue(instance, property.GetValue(obj), null);
return instance;
}
在客户端中:
var result = context.MyItem.SelectExcept(x => x.Image);
您可以排除多个物业:
var result = context.MyItem.SelectExcept(x => new { x.Image, x.Name });
这篇关于如何在Lambda LINQ中排除属性而不是选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文