gpt4 book ai didi

c# - Linq 选择哪里

转载 作者:太空狗 更新时间:2023-10-29 20:10:09 24 4
gpt4 key购买 nike

我经常发现自己写这样的东西:

var fields = _type.GetProperties()
.Select(prop => new { Prop = prop, Attrib = prop.GetCustomAttribute<ColumnAttribute>() })
.Where(t => t.Attrib != null)
.ToList();

令我烦恼的是,我在 where 子句失败的情况下创建了不必要的对象。虽然开销很小,但我仍然更愿意保存分配,就像我只是简单地循环它或做更痛苦的事情一样:

var fields = _type.GetProperties()
.Select(prop =>
{
var attrib = prop.GetCustomAttribute<ColumnAttribute>();

return attrib == null ? null : new {Prop = prop, Attrib = attrib};
})
.Where(t => t != null);

我是否缺少更好的模式/扩展方法?或者 LINQ 是否有可能在幕后进行优化?

非常感谢!

更新:

我想这就是我的意思,但我希望已经存在类似的东西,我只是搜索不佳:

public static IEnumerable<TResult> SelectWhereNotNull<TSource, TValue, TResult>(this IEnumerable<TSource> source, Func<TSource, TValue> valueSelector, Func<TSource, TValue, TResult> selector)
where TValue:class
where TResult:class
{
return source
.Select(s =>
{
var val = valueSelector(s);

if (val == null)
{
return null;
}

return selector(s, val);
})
.Where(r => r != null);
}

var fields = _type.GetProperties()
.SelectWhereNotNull(prop => prop.GetCustomAttribute<ColumnAttribute>(), Tuple.Create);

最佳答案

对于您正在执行的查询类型,您无法真正绕过它。您希望有一个地方可以将该属性放在某个地方。无论您是将它隐藏在一个单独的方法中,还是对您的结果对象进行操作,都必须这样做。担心它会适得其反。但是有一些方法可以使它更具可读性。

如果您在查询语法中重写了查询,则可以隐藏它正在完成的事实

var fields =
from prop in _type.GetProperties()
let attr = prop.GetCustomAttribute<ColumnAttribute>()
where attr != null
select new
{
Prop = prop,
Attrib = attr,
};

然而,为此,我可能会将其打包到一个生成器中。它不需要用 LINQ 编写,如果您尝试这样做,您将严重限制自己。

public static IEnumerable<TResult> SelectWhere<TSource, TValue, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TValue> valueSelector,
Func<TSource, TValue, bool> predicate,
Func<TSource, TValue, TResult> resultSelector)
{
foreach (var item in source)
{
var value = valueSelector(item);
if (predicate(item, value))
yield return resultSelector(item, value);
}
}

你的查询变成这样:

var fields = _type.GetProperties()
.SelectWhere(
p => p.GetCustomAttribute<ColumnAttribute>(),
(p, a) => a != null,
(p, a) => new { Prop = p, Attrib = a }
)
.ToList();

关于c# - Linq 选择哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com