Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>LINQ makes this pretty simple to do, by relying on the fact that the default value of any numeric type is zero, and they have appropriate equality methods:</p> <pre><code>private bool AtLeastOneBufferItemIsNonZero&lt;T&gt;(T[] items) { T zero = default(T); EqualityComparer&lt;T&gt; comparer = EqualityComparer&lt;T&gt;.Default; return items.Any(t =&gt; !comparer.Equals(t, zero)); } </code></pre> <p>Now that doesn't restrict it to numeric types, but it does avoid repetition. You can go further, by generalizing it to <code>IEnumerable&lt;T&gt;</code> and making it an extension method:</p> <pre><code>public static class Extensions { public static bool ContainsNonDefaultValue&lt;T&gt;(this IEnumerable&lt;T&gt; source) { if (source == null) { throw new ArgumentNullException("source"); } T zero = default(T); EqualityComparer&lt;T&gt; comparer = EqualityComparer&lt;T&gt;.Default; return items.Any(t =&gt; !comparer.Equals(t, zero)); } } </code></pre> <p>You <em>could</em> restrict this to value types by changing the constraint to</p> <pre><code>where T : struct </code></pre> <p>but that would be a bit pointless IMO. With the change to use <code>EqualityComparer&lt;T&gt;.Default</code>, you can <em>also</em> use the method to check whether any value in a reference type sequence is non-null.</p> <p>EDIT: As a side note, another way of look at it is to reverse the condition:</p> <pre><code>return !items.All(t =&gt; comparer.Equals(t, zero)); </code></pre> <p>It depends whether you're happier with the concept of "any of them is non-zero" or "they're not all zero" :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload