1

I have a code that should check a list of elements in an array and the resulting list should give me eliminating the repeating values. Here is my code

List <int> ProductListFinalized = new List<int>(ProductIdList);

for(int i = 0 ; i < ProductIdList.Count(); i++) 
{   
    int ProductId = ProductIdList[i];
    Res= !(ProductListFinalized.Contains(ProductId));
    if(!(ProductListFinalized.Contains(ProductId)))
    {
        ProductListFinalized.Add(ProductId); 
    }   
}

ProductIdListForCycleCount = ProductListFinalized.ToArray(); 

I am still finding the repeating values in the resulting Array. Whats is wrong with my code?

3
  • 4
    new List<int>(ProductIdList);, you certainly don't want that Commented May 11, 2018 at 12:05
  • 2
    you can use Distinct : ProductListFinalized.Select(x => x.ProductId).Distinct(); Commented May 11, 2018 at 12:06
  • @VincentElbertBudiman Or use a HashSet<int> Commented May 11, 2018 at 12:07

3 Answers 3

3

Because List<int> ProductListFinalized = new List<int>(ProductIdList); created a new list with the same values that ProductIdList, so always they'll be contain of list.

You have to create an empty list:

List<int> ProductListFinalized = new List<int>();
Sign up to request clarification or add additional context in comments.

Comments

1

At first, You are already entering "all entities" by running this line:

List <int> ProductListFinalized = new List<int>(ProductIdList);

As List will get larger based on needs, You can simply do:

var ProductListFinalized = new List<int>(); //Do not enter parameter here

Also to simplify the running process, You can avoid the C# usage of for, and use a LINQ query Distinct() for the expected results.

var ProductListFinalized = ProductIdList.Distinct();

Comments

0

As you can read from the docs, List<T>(IEnumerable<T>):

Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

But, you don't want a List<T> here, you want a HashSet<T> instead:

If collection contains duplicates, the set will contain one of each unique element. No exception will be thrown. Therefore, the size of the resulting set is not identical to the size of collection.

So, your entire code could be reduced to just this:

var productListFinalized = new HashSet<int>(ProductIdList);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.