Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a distinct list of integers from a list of objects?

Tags:

c#

I have a list of objects, each object has property total.

i need to create a new List<int> from the above list. the problem is if two objects have total=4, the List<int> should only contain one '4'.

let my list be:

[
    {name: "vishnu" , total: 10},
    {name: "vishnu2", total: 11},
    {name: "vishnu3", total: 15},
    {name: "vishnu4", total: 10}
]

so in my list of integers the output should be:

10,11,15

and not:

10,11,15,10

like image 507
hilda_sonica_vish Avatar asked Nov 08 '16 07:11

hilda_sonica_vish


4 Answers

using Linq:

myObjects.Select(obj => obj.total).Distinct().ToList()
like image 157
Mark van Straten Avatar answered Oct 17 '22 01:10

Mark van Straten


Why do you want to store distinct items in a List<T>? It seems to be a wrong collection type. I suggest using HashSet<T> which has been specially designed for that:

https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx

The implementation can be as simple as

HashSet<int> result = new HashSet<int>(list.Select(item => item.total));

Test

// 10, 11, 15
Console.Write(String.Join(", ", result));

If you insist on List<int>:

List<int> myList = result.ToList();
like image 44
Dmitry Bychenko Avatar answered Oct 17 '22 02:10

Dmitry Bychenko


Sometning like this ?

using System.Linq;
...

var list = new List <YourClass>();
...
var newList = list.Select(i => i.total).Distinct().ToList ();
like image 1
Aloene Avatar answered Oct 17 '22 02:10

Aloene


You can use something like this:

var result = myInput.GroupBy(x => x.Total).Select(x => new 
{ 
    Total = x.Key, 
    Name = x.First().Name 
});

This creates a new list of anonymous type where every element has a Toal and a Name-property. However only the first element of a group is considered if more then one are gropued together.

This solution has the advantage that it persists the Name-properties. If you don´t need this and are only interested on the Total, then Distinct as suggested by others is easier.

like image 1
MakePeaceGreatAgain Avatar answered Oct 17 '22 00:10

MakePeaceGreatAgain