Reputation: 2882
Here will explain in detail: I have
public class Season
{
#region Public Variables
private int _id;
private string _seasonName;
private int _startMonth;
#endregion
#region Public Properties
public int Id
{
get { return _id; }
set { _id = value; }
}
public int StartMonth
{
get { return _startMonth; }
set { _startMonth = value; }
}
public string SeasonName
{
get { return _seasonName; }
set { _seasonName = value; }
}
#endregion
#region Public Constructor
public Season()
{
this._initialize();
}
public Season(string pSeasonName, int _pStartMonth,int pID)
{
this._initialize(pSeasonName, _pStartMonth, pID);
}
#endregion
}
Next I have as show below
IList<Season> seaosns = new List<Season>();
seaosns.Add(new Season("Summer", 4, 1));
seaosns.Add(new Season("Winter", 6, 2));
seaosns.Add(new Season("MidSummer", 10, 1));
Here i need to check , if Ids are repeated in Ilist Items. This can be done by using For Loop, but need to know is there any other solution.
Thanks in Advance.
Upvotes: 1
Views: 1820
Reputation: 10940
Use a HashSet instead of a list! A set is a collection that contains no duplicate elements, and whose elements are in no particular order. You can provide a custom IEqualityComparer for determining the uniqueness your seasons.
var seaosns = new HashSet<Season>(seasonsEqualityComparer);
seaosns.Add(new Season("Summer", 4, 1));
seaosns.Add(new Season("Winter", 6, 2));
seaosns.Add(new Season("MidSummer", 10, 1)); // returns false...
Upvotes: 4
Reputation: 37770
If you just want to check, try this:
var hasDuplicates = list.GroupBy(season => season.Id).Any(groupping => groupping.Count() > 1);
But if you want to get collection, that is initially without duplicates, use HashSet or Dictionary, as the others said, or make subclass from Collection which wouldn't allow to add duplicates.
Upvotes: 0
Reputation: 12513
You could use an IDictionary
instead of an IList
, then duplicate keys are not allowed. You could use Season.Id
as the key. Using a Lookup
would allow you duplicate elements, so you could iterate the keys and check how many elements are associated with it.
Upvotes: 3
Reputation: 1062770
The most appropriate way to do that is to store the items (either instead, or in addition) in a Dictionary<int,Season>
, using the unique property (Id
) as a key in the dictionary. Then you have an O(1)
lookup both to test existence, and to fetch by key (Id
). Note, however, that a dictionary is not ordered - meaning, it does not guarantee to respect either insertion order, or key order. The order is not defined - so if you need them in a particular order you might need to hold that separately.
Upvotes: 4