How to take duplicate values from an Arraylist

Asked

Viewed 3,145 times

3

I would like to know how I can separate the double values, an example:

I have a Variable FormaPagto defined as a ArrayList,

In this variable I have 6 data:

0 - Money 1 - Debit 2 - Debit 3 - Money 4 - Money 5 - Cheque

What I want to do, separate the different values, in case we just take the values without them repeating themselves, would be like this:

0 - Money 1 - Debit 2 - Cheque

Grouping the values leaving them unique, and if possible leave in a ArrayList.

Is there any function of the ArrayList, who does such magic? Or what they suggest to me ?

1 answer

5


First, one should not use ArrayList. Since the introduction of generic in C# 2.0, it is recommended to use List<T> generic.

With a List<T>, you can use the extension Enumerable.Distinct to eliminate duplicate values.

using System.Linq;
using System.Collections.Generic;

var list = new List<String> {"Dinheiro", "Debito", "Debito", "Dinheiro", "Cheque"};
var distinct = list.Distinct().ToList();
  • I came to read about this function, because my entire project was done in Arraylist, would you like to know what pq should not use it? Would it be because it is limited? Or? >).

  • 1

    Yes, ArrayList is limited in several respects. 1) is not generic, and therefore all elements are object, 2) Whenever an element is removed from the list, the cast has to be made for the correct type - Casts take the code that may fail in Runtime, and therefore the bugged code, 3) does not support LINQ extensions for data manipulation. Recommend vividly re-factoring the project, and replacing all ArrayLists for List<T>s

  • 1

    Ah, and 4) as all elements are object, one ArrayList with value types (integers, doubles, booleans) will do Boxing of all elements, and this has a significant impact on performance

Browser other questions tagged

You are not signed in. Login or sign up in order to post.