Casting a Linq Request to a Structure in .Net

Good morning,
I created a structure that will be a shortened version of the class that I already have. I am trying to use a linq query to iterate over a MyClass list and create a list based on the results (a list of several lists based on several MyClass properties). Something like that...

List<MyStructure> thisList = (from MyClass thisClass in List<MyClass> select thisClass.Property1, thisClass.Property2, thisClass.Property3 Distinct.Cast<MyStructure>()).ToList<MyStructure>(); 

where MyStructure contains 3 variables Property1, Property3 and Property3 with the same types.

I fully understand that the above code will not compile, but this is the type I'm trying to do. Can someone please tell me is it possible to do this?

thanks

+4
source share
3 answers

Exactly what you need

This is called anonymous types.

Link: alt text

+5
source

If you want to use an existing MyStructure , you can simply use the following:

  List<MyStructure> thisList = myClassList.Distinct() .Select(c => new MyStructure { Property1 = c.Property1, Property2 = c.Property2, Property3 = c.Property3 }).ToList(); 
+5
source
  var List = new List<MyClass> { new MyClass { Property1 = 1, Property2 = 2, Property3 = 3}, new MyClass { Property1 = 10, Property2 = 20, Property3 = 30}, new MyClass { Property1 = 1, Property2 = 2, Property3 = 3} }; // method 1 - anonymous class var thisList = (from MyClass thisClass in List select new { thisClass.Property1, thisClass.Property2, thisClass.Property3 }).Distinct().ToList(); // method 2 - anonymous class var result = List.Select(x => new { x.Property1, x.Property2, x.Property3 }).Distinct().ToList(); // method 3 - group (get the first MyClass object from the 'distinct' group) var grouped = (from item in List group item by new { item.Property1, item.Property2, item.Property3 } into itemGroup select itemGroup.First()).ToList(); 
+2
source

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


All Articles