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
using Linq:
myObjects.Select(obj => obj.total).Distinct().ToList()
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();
Sometning like this ?
using System.Linq;
...
var list = new List <YourClass>();
...
var newList = list.Select(i => i.total).Distinct().ToList ();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With