Add a list of items into the dictionary.
#region License and Copyright
/* -------------------------------------------------------------------------
* Dotnet Commons Collections
*
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
*
* Free Software Foundation, Inc.,
* 59 Temple Place,
* Suite 330,
* Boston,
* MA 02111-1307
* USA
*
* -------------------------------------------------------------------------
*/
#endregion
using System;
using System.Collections;
using System.Text;
namespace Dotnet.Commons.Collections
{
///
/// <summary>
///
/// This utility class extends the operations for manipulating
/// Dictionary collections.
///
///
/// </summary>
///
public class DictionaryUtils
{
private DictionaryUtils()
{
}
/// <summary>
/// Add a list of items into the dictionary.
///
/// </summary>
/// <param name="list">List that contains items that are to be added to the dictionary</param>
/// <param name="dictionary">dictionary to be added with items from list</param>
/// <param name="propertyNameKey">Name of property to be use as key</param>
public static void AddToDictionary(IList list,
ref IDictionary dictionary,
string propertyNameKey)
{
foreach (object obj in list)
{
//Generate a key for the object
object objKey = null;
if (propertyNameKey != null)
{
object propertyValue = obj.GetType().GetProperty(propertyNameKey);
// only Property value as key if not null
if (propertyValue != null)
objKey = propertyValue;
}
if (objKey == null)
{
objKey = obj.GetType().FullName + "@" + obj.GetHashCode().ToString();
}
// if a similar object already exists, simply replace it. Otherwise add
// to the dictionary
if (dictionary[objKey] != null)
dictionary[objKey] = obj;
else
dictionary.Add(objKey, obj);
}
}
}
}
Related examples in the same category