gpt4 book ai didi

c# - 如何创建 Between 扩展方法

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

我有一个变量,其值在运行时填充。我想使用扩展方法检查该值是否介于两个相同的数据类型值(比如最低和最高)之间。

我想检查一下

int a = 2; //here static but is can be changed at runtime

if(a.Between(0,8))
DoSomething();
else
DoNothing();

如果 a 是 0 或 8 或者它们之间的任何值,它应该返回 true

如果 a 是(-1 或更小)或(9 或更大)那么它应该返回 false

我想创建一个类似的扩展方法

public static bool Between<T1>(this T1 val1, T1 lowest, T1 highest) where ????
{
What code to write here????
}

最佳答案

你可以这样做:

public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) <= 0;
}

引用 here

或者如果你想在一个集合上这样做,你可以这样做:

public static IEnumerable<TSource> Between<TSource, TResult>
(
this IEnumerable<TSource> source, Func<TSource, TResult> selector,
TResult lowest, TResult highest
)
where TResult : IComparable<TResult>
{
return source.OrderBy(selector).
SkipWhile(s => selector.Invoke(s).CompareTo(lowest) < 0).
TakeWhile(s => selector.Invoke(s).CompareTo(highest) <= 0 );
}

引用 here

用法:

var tenTo40 = list.Between(s => s, 10, 40);

关于c# - 如何创建 Between 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10511034/

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