gpt4 book ai didi

c# - 如何为集合创建类似于空条件运算符的空条件运算符?

转载 作者:行者123 更新时间:2023-12-02 19:43:38 29 4
gpt4 key购买 nike

C# 6.0 引入了 null 条件运算符,这是一个巨大的胜利。

现在我想要一个与其行为类似的运算符,但用于空集合。

Region smallestFittingFreeRegion = FreeRegions
.Where(region => region.Rect.W >= width && region.Rect.H >= height)
.MinBy(region => (region.Rect.W - width) * (region.Rect.H - height));

现在,如果 Where 返回一个空的 IEnumerable,就会爆炸,因为 MinBy (来自 MoreLinq)会抛出一个如果集合为空,则异常。

在 C# 6.0 之前,这可能可以通过添加另一个扩展方法 MinByOrDefault 来解决。

我想像这样重写它:.Where(...)?.MinBy(...)。但这不起作用,因为 .Where 返回一个空集合而不是 null

现在可以通过为 IEnumerable 引入 .NullIfEmpty() 扩展方法来解决这个问题。到达 .Where(...).NullIfEmpty()?.MinBy()

最终这看起来很尴尬,因为返回空集合总是比返回null更好。

还有其他更优雅的方法吗?

最佳答案

恕我直言,“最优雅”的解决方案是重写 MinBy将其放入 MinByOrDefault

public static TSource MinByOrDefault<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector)
{
return source.MinByOrDefault(selector, Comparer<TKey>.Default);
}

public static TSource MinByOrDefault<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
if (comparer == null) throw new ArgumentNullException("comparer");
using (var sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
return default(TSource); //This is the only line changed.
}
var min = sourceIterator.Current;
var minKey = selector(min);
while (sourceIterator.MoveNext())
{
var candidate = sourceIterator.Current;
var candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, minKey) < 0)
{
min = candidate;
minKey = candidateProjected;
}
}
return min;
}
}

我认为不需要特殊的运算符(operator)。

关于c# - 如何为集合创建类似于空条件运算符的空条件运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822451/

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