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

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

I need to create a new List<int> from the above list. the problem is that if two objects have total = 4, the List<int> should only contain "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

+5
source share
4 answers

using Linq:

 myObjects.Select(obj => obj.total).Distinct().ToList() 
+10
source

Why do you want to store individual items in a List<T> ? This seems to be the wrong type of collection. I suggest using HashSet<T> , which was specifically designed for this:

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

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 a List<int> :

 List<int> myList = result.ToList(); 
+4
source

You can use something like this:

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

Creates a new list of anonymous type, where each element has Toal and Name -property. However, it is believed that only the first element of the group, if more than one are combined together.

This solution has the advantage of retaining the Name properties. If you do not need this and you are only interested in Total , then Distinct , as suggested by others, is simpler.

+1
source

Matching this way?

 using System.Linq; ... var list = new List <YourClass>(); ... var newList = list.Select(i => i.total).Distinct().ToList (); 
+1
source

Source: https://habr.com/ru/post/1259448/


All Articles