IEnumerableExtensions

Namespace: XLabs.Core
We found 10 examples in language CSharp for this search. You will see 29 fragments of code.

Other methods


        [Fact]
        public void ForEach_generic_throws_ArgumentNullException()
        {
            IEnumerable<object> enumeration = new[] { "a", "b", "c" };
            void action(object _) { }
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.ForEach<object>((IEnumerable<object>)null, action));
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.ForEach<object>(enumeration, (Action<object>)null));
        }

        [Fact]
        public void ForEach_throws_ArgumentNullException()
        {
            IEnumerable enumeration = new[] { "a", "b", "c" };
            void action(object _) { }
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.ForEach((IEnumerable)null, action));
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.ForEach(enumeration, (Action<object>)null));
        }

        [Fact]
        public void Apply_generic_throws_ArgumentNullException()
        {
            IEnumerable<object> enumeration = new[] { "a", "b", "c" };
            void action(object _) { }
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Apply<object>((IEnumerable<object>)null, action).Iterate());
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Apply<object>(enumeration, (Action<object>)null).Iterate());
        }

        [Fact]
        public void Apply_throws_ArgumentNullException()
        {
            IEnumerable enumeration = new[] { "a", "b", "c" };
            void action(object _) { }
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Apply((IEnumerable)null, action).Iterate());
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Apply(enumeration, (Action<object>)null).Iterate());
        }

        [Fact]
        public void DistinctBy_throws_ArgumentNullException()
        {
            IEnumerable<object> enumeration = new[] { "a", "b", "c" };
            object action(object value) => value;
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.DistinctBy((IEnumerable<object>)null, action).Iterate());
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.DistinctBy(enumeration, (Func<object, object>)null).Iterate());
        }

        [Fact]
        public void Iterate_throws_ArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => IEnumerableExtensions.Iterate(null));
        }

        static void Main()
        {
            int [] arr = new int[]{3, 4, 1, 7, 10};
            Console.WriteLine( IEnumerableExtensions.Sum(arr) );
            Console.WriteLine( IEnumerableExtensions.Average(arr) );
            Console.WriteLine( IEnumerableExtensions.Max(arr) );
            Console.WriteLine( IEnumerableExtensions.Min(arr) );
            Console.WriteLine( IEnumerableExtensions.Product(arr) );
        }

        [TestMethod]
        public void IEnumerableExtensions_AllEqual_NullArgChecks()
        {
            Exceptions.Expect<ArgumentNullException>(() => IEnumerableExtensions.AllEqual(null, EqualityComparer<object>.Default));
            Exceptions.Expect<ArgumentNullException>(() => IEnumerableExtensions.AllEqual(new object[0], null));
        }

        [TestMethod]
        public void IEnumerableExtensions_AllEqual_Empty_IsTrue()
        {
            // Act + Assert
            IEnumerableExtensions.AllEqual(new int[0]).Should().BeTrue("Expected empty enumerable to be AllEqual");
        }

		public static IList<T> Shuffle<T>(this IList<T> List)
		{
			for (int I = 0; I < List.Count; I++)
			{
				List.Swap(I, IEnumerableExtensions.Generator.Next(I, List.Count));
			}
			return List;
		}

		public static T Random<T>(this IList<T> List)
		{
			return List[IEnumerableExtensions.Generator.Next(0, List.Count)];
		}

        static void Main()
        {
            int [] arr = new int[]{3, 4, 1, 7, 10};
            Console.WriteLine( IEnumerableExtensions.Sum(arr) );
            Console.WriteLine( IEnumerableExtensions.Average(arr) );
            Console.WriteLine( IEnumerableExtensions.Max(arr) );
            Console.WriteLine( IEnumerableExtensions.Min(arr) );
            Console.WriteLine( IEnumerableExtensions.Product(arr) );
        }

        [TestMethod]
        public void Batch_ReturnsGroupsOfN()
        {
            var numbers = Enumerable.Range(1, 100);
            var groups = IEnumerableExtensions.Batch(numbers, 10);
            Assert.IsTrue(groups.All(g => g.Count() == 10));
        }

        [TestMethod]
        public void Batch_OnlyLastGroupHasLessItems()
        {
            var numbers = Enumerable.Range(1, 100);
            var groups = IEnumerableExtensions.Batch(numbers, 13);

            var lastGroup = groups.Last();
            var restOfGroups = groups.Take(groups.Count() - 1);

            Assert.IsTrue(restOfGroups.All(g => g.Count() == 13));
            Assert.IsTrue(lastGroup.Count() == 9); //13*7 + 9 = 100
        }

        [TestMethod]
        public void EmptyIfNull_ReturnsEmptyEnumerationIfNull()
        {
            var nullInts = (IEnumerable<int>)null;
            var result = IEnumerableExtensions.EmptyIfNull(nullInts);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count() == 0);
        }

        [TestMethod]
        public void EmptyIfNull_ReturnsOriginalEnumerationIfNotNull()
        {
            var ints = Enumerable.Range(1, 100);
            var result = IEnumerableExtensions.EmptyIfNull(ints);
            Assert.IsNotNull(result);
            Assert.AreEqual(result, ints);
        }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> sequence)
    {
      if (sequence != null)
        return !Enumerable.Any<T>(sequence);
      return true;
    }

    public static IEnumerable<T> Concat<T>(this IEnumerable<T> sequence, params T[] values)
    {
      return Enumerable.Concat<T>(sequence, (IEnumerable<T>) values);
    }

    public static long Xor(this IEnumerable<long> sequence)
    {
      return IEnumerableExtensions.Xor<long>(sequence, (Func<long, long>) (value => value));
    }

    public static int Xor(this IEnumerable<int> sequence)
    {
      return IEnumerableExtensions.Xor<int>(sequence, (Func<int, int>) (value => value));
    }

    public static long Xor<T>(this IEnumerable<T> sequence, Func<T, long> selector)
    {
      return Enumerable.Aggregate<T, long>(sequence, 0L, (Func<long, T, long>) ((xorTotal, current) => xorTotal ^ selector(current)));
    }

    public static int Xor<T>(this IEnumerable<T> sequence, Func<T, int> selector)
    {
      return Enumerable.Aggregate<T, int>(sequence, 0, (Func<int, T, int>) ((xorTotal, current) => xorTotal ^ selector(current)));
    }

        /// <summary>
        /// Any?.
        /// </summary>
        /// <param name="source">Source.</param>
        /// <returns>Bool.</returns>
        public static bool Any(this IEnumerable source)
        {
            if (source == null)
            {
                return false;
            }

            var e = source.GetEnumerator();
            return e.MoveNext();
        }

        /// <summary>
        /// Count.
        /// </summary>
        /// <param name="source">Source.</param>
        /// <returns>Int.</returns>
        public static int Count(this IEnumerable source)
        {
            switch (source)
            {
                case null:
                    return 0;
                case ICollection col:
                    return col.Count;
            }

            var c = 0;
            var e = source.GetEnumerator();

            while (e.MoveNext())
            {
                c++;
            }

            return c;
        }

        public static IcmpLayer NextIcmpLayer(this Random random)
        {
            IcmpMessageType icmpMessageType = random.NextEnum(IcmpMessageType.DomainNameReply);
            ushort? checksum = random.NextBool() ? (ushort?)random.NextUShort() : null;

            switch (icmpMessageType)
            {
                case IcmpMessageType.DestinationUnreachable:
                    return new IcmpDestinationUnreachableLayer
                           {
                               Code = random.NextEnum<IcmpCodeDestinationUnreachable>(),
                               Checksum = checksum,
                               NextHopMaximumTransmissionUnit =
                               random.NextUShort(IcmpDestinationUnreachableDatagram.MinimumMaximumTransmissionUnit, ushort.MaxValue),
                           };

                case IcmpMessageType.TimeExceeded:
                    return new IcmpTimeExceededLayer
                           {
                               Code = random.NextEnum<IcmpCodeTimeExceeded>(),
                               Checksum = checksum,
                           };

                case IcmpMessageType.ParameterProblem:
                    return new IcmpParameterProblemLayer
                           {
                               Checksum = checksum,
                               Pointer = random.NextByte(),
                               OriginalDatagramLength = random.NextByte() * sizeof(uint),
                           };

                case IcmpMessageType.SourceQuench:
                    return new IcmpSourceQuenchLayer
                           {
                               Checksum = checksum
                           };

                case IcmpMessageType.Redirect:
                    return new IcmpRedirectLayer
                           {
                               Code = random.NextEnum<IcmpCodeRedirect>(),
                               Checksum = checksum,
                               GatewayInternetAddress = random.NextIpV4Address()
                           };

                case IcmpMessageType.Echo:
                    return new IcmpEchoLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort()
                           };

                case IcmpMessageType.EchoReply:
                    return new IcmpEchoReplyLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort()
                           };


                case IcmpMessageType.Timestamp:
                    return new IcmpTimestampLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                               OriginateTimestamp = random.NextIpV4TimeOfDay(),
                               ReceiveTimestamp = random.NextIpV4TimeOfDay(),
                               TransmitTimestamp = random.NextIpV4TimeOfDay()
                           };

                case IcmpMessageType.TimestampReply:
                    return new IcmpTimestampReplyLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                               OriginateTimestamp = random.NextIpV4TimeOfDay(),
                               ReceiveTimestamp = random.NextIpV4TimeOfDay(),
                               TransmitTimestamp = random.NextIpV4TimeOfDay()
                           };

                case IcmpMessageType.InformationRequest:
                    return new IcmpInformationRequestLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                           };

                case IcmpMessageType.InformationReply:
                    return new IcmpInformationReplyLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                           };


                case IcmpMessageType.RouterAdvertisement:
                    return new IcmpRouterAdvertisementLayer
                           {
                               Entries = random.NextIcmpRouterAdvertisementEntries(random.Next(10)).ToList().AsReadOnly(),
                               Checksum = checksum,
                               Lifetime = random.NextTimeSpan(TimeSpan.Zero, TimeSpan.FromSeconds(ushort.MaxValue)),
                           };

                case IcmpMessageType.RouterSolicitation:
                    return new IcmpRouterSolicitationLayer
                           {
                               Checksum = checksum,
                           };

                case IcmpMessageType.AddressMaskRequest:
                    return new IcmpAddressMaskRequestLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                               AddressMask = random.NextIpV4Address()
                           };

                case IcmpMessageType.AddressMaskReply:
                    return new IcmpAddressMaskReplyLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                               AddressMask = random.NextIpV4Address()
                           };

                case IcmpMessageType.TraceRoute:
                    return new IcmpTraceRouteLayer
                           {
                               Code = random.NextEnum<IcmpCodeTraceRoute>(),
                               Checksum = checksum,
                               Identification = random.NextUShort(),
                               OutboundHopCount = random.NextUShort(),
                               ReturnHopCount = random.NextUShort(),
                               OutputLinkSpeed = random.NextUInt(),
                               OutputLinkMaximumTransmissionUnit = random.NextUInt(),
                           };

                case IcmpMessageType.ConversionFailed:
                    return new IcmpConversionFailedLayer
                           {
                               Code = random.NextEnum<IcmpCodeConversionFailed>(),
                               Checksum = checksum,
                               Pointer = random.NextUInt(),
                           };

                case IcmpMessageType.DomainNameRequest:
                    return new IcmpDomainNameRequestLayer
                           {
                               Checksum = checksum,
                               Identifier = random.NextUShort(),
                               SequenceNumber = random.NextUShort(),
                           };

                case IcmpMessageType.DomainNameReply:
                    throw new NotSupportedException("Message Type " + icmpMessageType + " is not supported");

                case IcmpMessageType.SecurityFailures:
                    return new IcmpSecurityFailuresLayer
                           {
                               Code = random.NextEnum<IcmpCodeSecurityFailure>(),
                               Checksum = checksum,
                               Pointer = random.NextUShort()
                           };

                default:
                    throw new InvalidOperationException("Invalid icmpMessageType " + icmpMessageType);
            }
        }

        public static IEnumerable<ILayer> NextIcmpPayloadLayers(this Random random, IcmpLayer icmpLayer)
        {
            IEnumerable<ILayer> icmpPayloadLayers = new List<ILayer>();
            switch (icmpLayer.MessageType)
            {
                case IcmpMessageType.DestinationUnreachable:
                case IcmpMessageType.TimeExceeded:
                case IcmpMessageType.SourceQuench:
                case IcmpMessageType.Redirect:
                case IcmpMessageType.SecurityFailures:
                    icmpPayloadLayers = IEnumerableExtensions.Concat(icmpPayloadLayers, random.NextIpV4Layer(), random.NextPayloadLayer(IcmpIpV4HeaderPlus64BitsPayloadDatagram.OriginalDatagramPayloadLength));
                    break;
                case IcmpMessageType.ParameterProblem:
                    IpV4Layer ipV4Layer = random.NextIpV4Layer();
                    icmpPayloadLayers =
                        IEnumerableExtensions.Concat(icmpPayloadLayers, ipV4Layer,
                                                     random.NextPayloadLayer(random.NextInt(0,
                                                                                            IcmpParameterProblemLayer.OriginalDatagramLengthMaxValue + 1 -
                                                                                            ipV4Layer.Length)));
                    break;
                case IcmpMessageType.ConversionFailed:
                    IpV4Layer icmpIpV4Layer = random.NextIpV4Layer();
                    icmpPayloadLayers = IEnumerableExtensions.Concat(icmpPayloadLayers, icmpIpV4Layer);
                    if (icmpLayer.MessageTypeAndCode == IcmpMessageTypeAndCode.ConversionFailedUnsupportedTransportProtocol)
                    {
                        icmpPayloadLayers =
                            IEnumerableExtensions.Concat(icmpPayloadLayers, random.NextPayloadLayer(
                                IcmpConversionFailedDatagram.OriginalDatagramLengthForUnsupportedTransportProtocol -
                                icmpIpV4Layer.Length));
                    }
                    else
                    {
                        switch (icmpIpV4Layer.Protocol)
                        {
                            case IpV4Protocol.Udp:
                                icmpPayloadLayers = IEnumerableExtensions.Concat(icmpPayloadLayers, random.NextUdpLayer(),
                                                                             random.NextPayloadLayer(random.Next(100)));
                                break;

                            case IpV4Protocol.Tcp:
                                icmpPayloadLayers = IEnumerableExtensions.Concat(icmpPayloadLayers, random.NextTcpLayer(),
                                                                             random.NextPayloadLayer(random.Next(100)));
                                break;

                            default:
                                icmpPayloadLayers = IEnumerableExtensions.Concat(icmpPayloadLayers, random.NextPayloadLayer(random.Next(200)));

                                break;
                        }
                    }
                    break;

                case IcmpMessageType.Echo:
                case IcmpMessageType.EchoReply:
                case IcmpMessageType.Timestamp:
                case IcmpMessageType.TimestampReply:
                case IcmpMessageType.InformationRequest:
                case IcmpMessageType.InformationReply:
                case IcmpMessageType.RouterAdvertisement:
                case IcmpMessageType.RouterSolicitation:
                case IcmpMessageType.AddressMaskRequest:
                case IcmpMessageType.AddressMaskReply:
                case IcmpMessageType.TraceRoute:
                case IcmpMessageType.DomainNameRequest:
                    break;

                case IcmpMessageType.DomainNameReply:
                default:
                    throw new InvalidOperationException("Invalid icmpMessageType " + icmpLayer.MessageType);
            }
            return icmpPayloadLayers;
        }


        public static IEnumerable<IcmpRouterAdvertisementEntry> NextIcmpRouterAdvertisementEntries(this Random random, int numEntries)
        {
            for (int i = 0; i != numEntries; ++i)
                yield return new IcmpRouterAdvertisementEntry(random.NextIpV4Address(), random.Next());
        }



        // System.IEnumerableExtensions.Contains(list, "")
        public static bool Contains(System.Collections.IEnumerable enStringList, string strKey)
        {
            foreach (string strItem in enStringList)
            {
                if (System.StringComparer.OrdinalIgnoreCase.Equals(strItem, strKey))
                    return true;
            } // Next strItem

            return false;
        } // End Function Contains


        // System.IEnumerableExtensions.ConcatItems
        public static string ConcatItems(System.Collections.IEnumerable enStringList, string strSeparator)
        {
            string strReturnValue = "";

            System.Collections.Generic.List<string> lsItemList = new System.Collections.Generic.List<string>();

            foreach (string strItem in enStringList)
            {
                if(!string.IsNullOrEmpty(strItem))
                    lsItemList.Add(strItem);
            } // Next strItem

            strReturnValue = string.Join(strSeparator, lsItemList.ToArray());
            lsItemList.Clear();
            lsItemList = null;

            return strReturnValue;
        } // End ConcatItems

XLabs.IEnumerableExtensions : Object

Methods :

public static IReadOnlyCollection<T> ToReadOnlyCollection(IEnumerable<T> enumerable = )
public static IEnumerable<T> ForEach(IEnumerable<T> enumerable = , Action<T> action = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()