comparison Chronosv2/source/Extensions/CollectionExtensions.cs @ 10:443821e55f06

Initial cleaned up add from Codeplex files
author stevenh7776 stevenhollidge@hotmail.com
date Tue, 21 Feb 2012 17:25:44 +0700
parents
children
comparison
equal deleted inserted replaced
9:904a9faadf8b 10:443821e55f06
1 using System;
2 using System.Collections.Generic;
3
4 namespace Chronos.Extensions
5 {
6 /// <summary>
7 /// Extension methods for all kind of Collections implementing the ICollection&lt;T&gt; interface
8 /// </summary>
9 public static class CollectionExtensions
10 {
11 #region · Extensions ·
12
13 /// <summary>
14 /// Adds a value uniquely to to a collection and returns a value whether the value was added or not.
15 /// </summary>
16 /// <typeparam name="T">The generic collection value type</typeparam>
17 /// <param name="collection">The collection.</param>
18 /// <param name="value">The value to be added.</param>
19 /// <returns>Indicates whether the value was added or not</returns>
20 /// <example><code>
21 /// list.AddUnique(1); // returns true;
22 /// list.AddUnique(1); // returns false the second time;
23 /// </code></example>
24 public static bool AddUnique<T>(this ICollection<T> collection, T value)
25 {
26 if (!collection.Contains(value))
27 {
28 collection.Add(value);
29 return true;
30 }
31
32 return false;
33 }
34
35 /// <summary>
36 /// Adds a range of value uniquely to a collection and returns the amount of values added.
37 /// </summary>
38 /// <typeparam name="T">The generic collection value type.</typeparam>
39 /// <param name="collection">The collection.</param>
40 /// <param name="values">The values to be added.</param>
41 /// <returns>The amount if values that were added.</returns>
42 public static int AddRangeUnique<T>(this ICollection<T> collection, IEnumerable<T> values)
43 {
44 var count = 0;
45
46 foreach (var value in values)
47 {
48 if (collection.AddUnique(value))
49 {
50 count++;
51 }
52 }
53
54 return count;
55 }
56
57 public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> values)
58 {
59 foreach (T value in values)
60 {
61 collection.Add(value);
62 }
63 }
64
65 #endregion
66 }
67 }