Grant H.
Grant H.

Reputation: 3717

Linq query mistakes class member for the group keyword

I've got a query as follows:

var resOut = from p in xRefs
            select new FileUploadRecord
            {
                group = "",
                progress = xRef.Progress,

            };

This will not compile, because it sees group as the linq group keyword, and not the member of my class. I would simply rename the field, but it's part of a data contract and cannot be changed.

Is there a way to do this without a traditional for loop?

Upvotes: 1

Views: 218

Answers (5)

Paulo Morgado
Paulo Morgado

Reputation: 14846

Little known fact.

Besides verbatin identifiers (those prefixed with @), Unicode escapes are permited as identifiers.

So, this would also work:

var resOut = from p in xRefs
select new FileUploadRecord
{
    \u0067roup = "",
    progress = xRef.Progress,

};

For more information, read section §2.4.2 on the C# Language Specification.

Upvotes: 1

James
James

Reputation: 82096

Add the @ symbol to the beginning of the group property name, this allows you to use reserved/contextual keywords

var resOut = from p in xRefs
             select new FileUploadRecord
             {
                 @group = "",
                 ...
             }

Upvotes: 4

podiluska
podiluska

Reputation: 51494

Try

var resOut = from p in xRefs
        select new FileUploadRecord
        {
            @group = "",
            progress = xRef.Progress,

        };

You can escape reserved words using the @ prefix.

Upvotes: 2

Thomas Taylor
Thomas Taylor

Reputation: 555

I don't know why the other answers that specify the @ are downvoted. You can use @ to define literal identifiers.

var resOut = from p in xRefs
        select new FileUploadRecord
        {
            @group = "",
            progress = xRef.Progress,

        };

See the top of http://msdn.microsoft.com/en-us/library/x53a06bb.aspx for more information.

Upvotes: 1

Servy
Servy

Reputation: 203842

Don't use query syntax, use method syntax:

xRefs.Select(p => new FileUploadRecord
    {
        group = "",
        progress = xRef.Progress,
    });

The group keyword is a contextual keyword that is only considered a keyword when it is in a query syntax statement.

Upvotes: 1

Related Questions