Reputation: 3912
Good Morning,
I have created a structure to be a cut down version of a Class that I already have.
I am trying to use a linq query to iterate through the list of MyClass and create a List based on the results (A discinct list based on a few of the properties on MyClass). Something like this...
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 of Property1, Property3 and Property3 with the same types.
I am fully aware that the above code wont compile, but that is the sort i am trying to do. Could someone please tell me if this is possible to do?
Thanks
Upvotes: 5
Views: 6313
Reputation: 31548
If you want to use your 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();
Upvotes: 7
Reputation: 5853
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();
Upvotes: 2