avoid duplicates in list
-
How to avoid duplicate items from the list? for example consider
list contains 1,2,1,2,3,1,3,1,4,1,2,1,4
actually i want only ones that item placed in list(1,2,3,4) others want to be removed. it is possible? then How?
-
What type of list is it? The easiest way is not to allow duplicates in the first place when populating the list by using the Contains method if your list type has one (or similar).
Dave
-
i have list[structure] named list[intpoint]. intpoint contains x and y values. i wants the idle values of x and y. not the repeated values. i want to remove the duplicated value of x and y in list[intpoint]. how it is possible?.
//let me assume you have object called IntPoint that store x and y values and list holder
List pointList = new List();
//when you want add to list check
//let assume you have new IntPoint object called intPoint
if (!pointList.Contains(intPoint))
{
pointList.Add(intPoint);
}hope will help
dhaim program is hobby that make some money as side effect :)
-
i have list[structure] named list[intpoint]. intpoint contains x and y values. i wants the idle values of x and y. not the repeated values. i want to remove the duplicated value of x and y in list[intpoint]. how it is possible?.
As I said avoid adding duplicates initially. This code will attempt to add Point(1,1) ten times but the list will only contain the one entry.
List<Point> listPoint = new List<Point>();
Point pointToAdd;
pointToAdd = new Point(1, 1);
for (int i = 0; i <= 10; i++)
{
if (!listPoint.Contains(pointToAdd))
{
listPoint.Add(pointToAdd);
}
}
Console.WriteLine(listPoint.Count);If you really need to remove, I think the way is to create a new 'clean list' by iterating through the current list, checking before adding to the new list and then assigning the clean list to the old one.
List<Point> CleanList(List<Point> listPoint)
{
List<Point> cleanList = new List<Point>();
foreach (Point currentPoint in listPoint)
{
if (!(cleanList.Contains(currentPoint)))
{
cleanList.Add(currentPoint);
}
}
return cleanList;
}Then you can simply call
listPoint = CleanList(listPoint);
Dave
-
How to avoid duplicate items from the list? for example consider
list contains 1,2,1,2,3,1,3,1,4,1,2,1,4
actually i want only ones that item placed in list(1,2,3,4) others want to be removed. it is possible? then How?
If you are using .Net 3.5 you can use Enumerable.Distinct Method [^] Or HashSet<T> Generic Class[^]
Giorgi Dalakishvili #region signature my articles #endregion
-
How to avoid duplicate items from the list? for example consider
list contains 1,2,1,2,3,1,3,1,4,1,2,1,4
actually i want only ones that item placed in list(1,2,3,4) others want to be removed. it is possible? then How?
The free PowerCollections [^] library has methods for this kind of thing. It's very easy to use if you're already comfortable with generic collections (which you should be if you're using .NET 2 or higher).
Kevin