Thursday, March 31, 2011

How do I do this SELECT statement that uses column renaming (or column alias) with LINQ?

Apologies if this has been asked already, but I couldnt find it.

How do I get 'anotherColumnName' in LINQ?

SELECT thisColumnName as anotherColumnName FROM TableName

I have the following which obviously gives me 'thisColumnName' not 'anotherColumnName'

    var query = from names in _context.TableName
                select names;
    return query.ToList();

Solution

@Ian P - thanks to your answer.

For the finished solution I also needed a bit extra as below...

Old version.

public List<OldClassName> GetSomething()
{
    var query = from names in _context.OldClassNames
                select names;

    return query.ToList();
}

New version with column renaming.

public List<NewClassName> GetSomething()
{
    var query = from names in _context.OldClassNames
                select new NewClassName
                {
                    NewColumName = names.OldColumnName
                };
    return query.ToList();
}
From stackoverflow
  • Use an anonymous type:

    var query = (from name in _context.Table
                select new { anotherColumnName = name.ColumnName });
    

    Good luck!

    Paul Rowland : thanks. I just found this question as well. http://stackoverflow.com/questions/128277/linq-custom-column-names
  • @Ian P - thanks to your answer.

    For the finished solution I also needed a bit extra as below...

    Old version.

    public List<OldClassName> GetSomething()
    {
        var query = from names in _context.OldClassNames
                    select names;
    
        return query.ToList();
    }
    

    New version with column renaming.

    public List<NewClassName> GetSomething()
    {
        var query = from names in _context.OldClassNames
                    select new NewClassName
                    {
                        NewColumName = names.OldColumnName
                    };
        return query.ToList();
    }
    

0 comments:

Post a Comment