Search code examples
c#.netlinqcsquery

Lambda Statements in Linq


Is it possible to do something like the following in Linq?

List<Group> groupsCollection = new List<Group>();
groups.Select( g => {
    String id = g.Attributes["id"].Value;
    String title = g.Attributes["title"].Value;
    groupsCollection.Add( new Group(id, title) );
} );

This is just an example. I know a Foreach loop would be sufficient but I was querying whether it would be possible or not.

I tried it, and it's saying:

Cannot convert lambda expression to type System.Collections.IEnumerable<CsQuery.IDomObject> because it's not a delegate type

Edit: Group is my custom class. Groups are a collection of CsQuery Dom Objects. You can think of them as a collection of html anchor elements. They are IEnumerable.


Solution

  • I think you're looking for this:

    groupsCollection = groups.Select(g =>
        new Group(g.Attributes["id"].Value,
                  g.Attributes["title"].Value)).ToList();
    

    Explanation:

    Select() projects each element of a sequence into a new form. (From MSDN)

    It's basically a transformation function that takes one IEnumerable and transforms it, in whatever way you like, to another IEnumerable, which seems to be exactly what you want here.