Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查所有列表项是否具有相同的值并返回它,或返回一个“;其他值”;如果他们没有’;T_C#_Linq - Fatal编程技术网

C# 如何检查所有列表项是否具有相同的值并返回它,或返回一个“;其他值”;如果他们没有’;T

C# 如何检查所有列表项是否具有相同的值并返回它,或返回一个“;其他值”;如果他们没有’;T,c#,linq,C#,Linq,如果列表中的所有项目都有相同的值,那么我需要使用该值,否则我需要使用“otherValue”。我想不出一个简单明了的方法。当列表为空时,它应该返回“other”值 另见 我能想到的最干净的方式。您可以通过内联val使它成为一个单行程序,但First()将被计算n次,执行时间将增加一倍 要合并注释中指定的“空集”行为,只需在上面两行之前再添加一行: if(yyy == null || !yyy.Any()) return otherValue; 或者,如果您担心为每个元素执行First()(这可

如果列表中的所有项目都有相同的值,那么我需要使用该值,否则我需要使用“otherValue”。我想不出一个简单明了的方法。当列表为空时,它应该返回“other”值

另见

我能想到的最干净的方式。您可以通过内联val使它成为一个单行程序,但First()将被计算n次,执行时间将增加一倍

要合并注释中指定的“空集”行为,只需在上面两行之前再添加一行:

if(yyy == null || !yyy.Any()) return otherValue;
或者,如果您担心为每个元素执行First()(这可能是一个有效的性能问题):

public int GetResult(列表){
int first=list.first();
返回列表.All(x=>x==first)?first:SOME\u OTHER\u值;
}

虽然您当然可以使用现有的序列操作符构建这样的设备,但在这种情况下,我倾向于将此作为自定义序列操作符编写。比如:

// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
    int? first = null;
    foreach(var item in sequence)
    {
        if (first == null)
            first = item;
        else if (first.Value != item)
            return other;
    }
    return first ?? other;
}
//如果列表为空,则返回“other”。
//如果列表非空且有两个不同的元素,则返回“other”。
//如果列表中的元素为非空且所有元素都相同,则返回该元素。
公共静态int一致(此IEnumerable序列,int其他)
{
int?first=null;
foreach(序列中的var项目)
{
if(first==null)
第一个=项目;
else if(first.Value!=项目)
归还他人;
}
先返回??其他;
}
这非常清楚、简短,涵盖了所有情况,并且不会不必要地创建序列的额外迭代


将其转化为一个通用方法,并在
IEnumerable
上运行,这只是一个练习。:-)

所有同等产品的良好快速测试:

collection.Distinct().Count() == 1

这可能已经晚了,但根据Eric的回答,这是一个同样适用于值和引用类型的扩展:

public static partial class Extensions
{
    public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null)  where T : struct, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (Nullable<T>)first ?? other;
    }

    public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (T)first ?? other;
    }
}
公共静态部分类扩展
{
公共静态可空一致(此IEnumerable序列,可空其他,IEqualityComparer comparer=null),其中T:struct,IComparable
{
objectfirst=null;
foreach(序列中的var项目)
{
if(first==null)
第一个=项目;
else如果(comparer!=null&&!comparer.Equals(第一个,项))
归还他人;
如果(!first.Equals(项))
归还他人;
}
返回(可为空)第一个??其他;
}
公共静态T一致(此IEnumerable序列,T other,IEqualityComparer comparer=null),其中T:class,IComparable
{
objectfirst=null;
foreach(序列中的var项目)
{
if(first==null)
第一个=项目;
else如果(comparer!=null&&!comparer.Equals(第一个,项))
归还他人;
如果(!first.Equals(项))
归还他人;
}
返回(T)第一个??其他;
}
}

使用LINQ的替代方案:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

对上述简化方法的细微变化


var result=yyy.Distinct().Count()==yyy.Count()

如果数组的类型为多维,如下图所示,则我们必须在linq下方写入以检查数据

示例:这里的元素为0,我正在检查所有值是否为0。
ip1=
0
0
0
0 0 0 0

    var value=ip1[0][0];  //got the first index value
    var equalValue = ip1.Any(x=>x.Any(xy=>xy.Equals()));  //check with all elements value 
    if(equalValue)//returns true or false  
    {  
    return "Same Numbers";  
    }else{  
    return "Different Numbers";   
    }

关于你相当厚颜无耻的吸引注意力的问题,我同意Ani的答案@KeithS——这就是为什么我添加了我答案的第二部分。在小集合上,调用First()是很简单的。在大型集合中,这可能会成为一个问题。“在小型集合中,调用First()非常简单。”-这取决于集合的来源。对于简单对象的列表或数组,您完全正确。但是,有些枚举不是有限内存缓存的原语集。委托集合或通过算法系列计算(如Fibonacci)生成的枚举数每次计算First()都会非常昂贵。或者更糟糕的是,如果查询是数据库查询,并且每次调用“First”都会再次命中数据库。如果进行一次性迭代(如从文件读取),情况会变得更糟。。。所以Ani从其他线程得到的答案看起来是最好的。@Eric-C'mon。对于每个元素,点击数据库三次没有什么错…:-P+1,是否使用
。任何
都允许枚举在有不同值的情况下提前退出?@adrift:
所有
都将在点击
x.Value!=val
。类似地,
Any(x=>x.Value!=val)
一旦命中序列中的元素
x
,该元素的
x.Value!=val
。也就是说,
All
Any
都表现出类似于
&&
|
的“短路”(这实际上就是
All
Any
的本质)。@Jason:没错。所有(条件)都有效!任何(!条件),并且对其中一个条件的计算将在知道答案后立即终止。微优化:
返回yyy.Skip(1)。All(x=>x.Value==val)?val:其他值null
实际上是(大概)正确的响应时,合并将返回
other
。假设函数是一致的(这是IEnumerable序列,另一个)
或类似的签名,这使它有点复杂。@Anthony:确实,这里有很多复杂的地方,但它们很容易解决。为了方便起见,我使用了一个可为null的int,这样我就不必声明“我已经看到了第一项”
collection.Distinct().Count() == 1
public static partial class Extensions
{
    public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null)  where T : struct, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (Nullable<T>)first ?? other;
    }

    public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (T)first ?? other;
    }
}
var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;
var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;
    var value=ip1[0][0];  //got the first index value
    var equalValue = ip1.Any(x=>x.Any(xy=>xy.Equals()));  //check with all elements value 
    if(equalValue)//returns true or false  
    {  
    return "Same Numbers";  
    }else{  
    return "Different Numbers";   
    }