|
using System;
using System.Collections.Generic;
using System.Collections;
namespace HappyNomad {
public static class CollectionsUtil {
public static bool ContainsAny<T>( ICollection<T> collection, ICollection<T> values ) {
foreach ( T val in values ) {
if ( collection.Contains( val ) )
return true;
}
return false;
}
public static bool ContainsAll<T>( ICollection<T> collection, ICollection<T> values ) {
foreach ( T val in values ) {
if ( !collection.Contains( val ) )
return false;
}
return true;
}
/// <summary>
/// Compares the contents of two collections independent of item order.
/// [Source: http://patforna.blogspot.com/2006/12/comparing-collections-independent-of.html ]
/// </summary>
/// <typeparam name="T">The collections' item type</typeparam>
/// <returns>True if both collections contain the same elements (in any order)</returns>
public static bool Equals<T>( ICollection<T> one, ICollection<T> two ) {
if ( one == null || two == null ) // special case
return one == two;
if ( ReferenceEquals( one, two ) ) // same objects
return true;
if ( one.Count != two.Count )
return false;
IList<T> listOne = new List<T>( one );
IList<T> listTwo = new List<T>( two );
// make sure that every object in one is also in two
for ( int i = 0; i < listOne.Count; i++ ) {
T obj = listOne[i];
if ( !listTwo.Contains( obj ) )
return false;
else
listTwo.Remove( obj );
}
return true;
}
/// <summary>
/// Counts how many times an element occurs within a collection.
/// </summary>
public static int Count( ICollection collection, object element ) {
int result = 0;
foreach ( object o in collection )
if ( o == element ) result++;
return result;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Adrian loves facilitating suave user experiences via the latest and greatest GUI technologies such as Windows 8 Metro-style apps as well as WPF. More generally, he finds joy in architecting software that is easy to comprehend and maintain. He does so by applying design patterns at the top-level, and by incessantly refactoring code at lower levels. He's always interested in hearing about opportunities for full or part-time development work. He resides in Pennsylvania but can potentially travel anywhere in the country. (Writing about himself in the third-person is Adrian's new hobby.)