Reputation: 271
I was wondering if there's a simpler way to do this using LINQ or some other way...
I want to extract, from a List, all rows, grouping them by a particular field and storing the result in another different, like a List containing the grouped, not repeated, result of the search parameter.
Here's an example:
public class CustomObj
{
public int DOC { get; set; }
public string Desc { get; set; }
public string Name{ get; set; }
}
public class Worker()
{
public void DoWork()
{
List<CustomObj> objs = new List<CustomObj>();
objs.Add(new CustomObj(1, "Type1", "Name1"));
objs.Add(new CustomObj(1, "Type2", "Name1"));
objs.Add(new CustomObj(2, "Type2", "Name2"));
objs.Add(new CustomObj(3, "Type1", "Name1"));
objs.Add(new CustomObj(3, "Type2", "Name1"));
objs.Add(new CustomObj(3, "Type3", "Name1"));
// HERE'S WHAT I'D LIKE TO DO
// NOTE THAT THIS IS NOT A CORRECT FORMATED FUNCTION
List<int> docs = objs.GroupBy(o => o.DOC).Select(o => o.DOC).ToList<int>();
}
}
At the end my docs List should look like this
docs[0] = 1
docs[1] = 2
docs[2] = 3
In my current project I have, so far, 10 different objects, and I'm going to have to do this to all of them. Of course I'd like to avoid writing extensive functions to each one.
So if there's no other way at least I would like to know.
Thanks
Upvotes: 0
Views: 88
Reputation: 394
Or, if you want to use GroupBy:
var docs = objs.GroupBy(o => o.DOC).Select(o => o.Key).ToList();
Upvotes: 1
Reputation: 6337
What about:
List<int> docs = objs.Select(o => o.DOC).Distinct().ToList();
Upvotes: 5