Can LINQ sort by column index?

I'm struggling to find LINQ ordering examples where data is ordered by column index. Can this be done?

thank

+3
source share
5 answers

There is no such thing as a column in LINQ, only fields and properties. You mean, you probably specify the index of the property in the anonymous type that you create:

from p in persons
orderby 1
select new { p.FirstNam, p.LastName }

This is not possible because a) you cannot order the projection property (output value in an anonymous type), and b) you cannot order by index. To get around a), you can use the keyword "in":

from p in persons
orderby p.FirstName
select new { First = p.FirstName, Last = p.LastName }
into tmp
   orderby tmp.First
   select tmp;

LINQ IQueryable (, LINQ to SQL, LINQ , IEnumerable), , OrderBy.

var query = from p in persons 
            select new { Name = p.FirstName + " " + p.LastName, ...}
query = AddOrderByPosition (query, 1);
foreach (var p in query) {...}

AddOrderByPosition , ( , , "" ) OrderBy ( Select). # , , .

, , .

+4

, .

+2

, Select ? , Linq:

var tmp = 
    from container in Container
    where container.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID};

// The indexer cannot be used with the query expression format, so we need to convert to dot notation.
// We also need to convert tmp to an Enumerable so that .NET performs the query instead of SQL.
var results = tmp.AsEnumerable().Select((row, index) => new { row.ContainerID, row.TypeID, ContainerIndex = index });
+1

LinqToSql , , , . . .

, ( ) .

, XmlMappingSource. .

+1

( - ). LINQ , .

You might be lucky if you put your objects in List<T>and then use the method .Sorton them. Here is a dirty example that might help you.

var query = db.MyTable.Where(x => something);
var list = query.ToList();
list.Sort((x, y) => {
    // decide how you want to compare
    // use string.compare or another method
    // return -1, 0, 1 as is normal for sorting

    return 0; //Replace this
});
0
source

Source: https://habr.com/ru/post/1755494/


All Articles