我需要使用LINQ为集合的实例添加一个唯一的id
本文关键字:一个 id 唯一 添加 实例 LINQ 集合 | 更新日期: 2023-09-27 18:20:32
我有以下类,用于保存仅用于报告的数据。
public class AdminDetail
{
public int Row { get; set; } // This row needs a unique number
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Title { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string Level { get; set; }
public string Order { get; set; }
}
在表集合上使用以下select填充(_T)。
details = from t in _table
select new AdminDetail
{
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Title = t.Title,
Status = t.Status,
Type = t.Type,
Level = t.Level,
Order = t.Order
};
detailsList = details.OrderBy(item => item.Order).ThenBy(item => item.Title).ToList();
在用我想给出的最后一条语句对行进行排序后,将一个值放入RowID对应于行。因此,如果我返回了三个实例,我希望它们具有RowID1,2和3。
有没有一种方法可以让我用LINQ做到这一点?
您可以使用提供索引的Select
重载来完成此操作,但您可能希望在排序后对AdminDetail
进行投影:
var ordered = from item in _table
orderby item.Order, item.Title
select item;
var details = ordered.Select((t, index) => new AdminDetail
{
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Title = t.Title,
Status = t.Status,
Type = t.Type,
Level = t.Level,
Order = t.Order,
Row = index + 1
})
.ToList();
除此之外,如果_table
是LINQ到SQL表(或类似的表),则可以在数据库中执行排序,而不是在LINQ到对象中执行排序。
使用带索引的Select
方法,例如:
table.Select((t, index) => new AdminDetail {
Row = index + 1,
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Title = t.Title,
Status = t.Status,
Type = t.Type,
Level = t.Level,
Order = t.Order });
描述
可以将select
方法与索引一起使用。
样品
detailsList = details.OrderBy(item => item.Order).ThenBy(item => item.Title)
.Select((t, index) => new AdminDetail()
{
PartitionKey = t.PartitionKey,
RowKey = t.RowKey,
Title = t.Title,
Status = t.Status,
Type = t.Type,
Level = t.Level,
Order = t.Order,
Row = index + 1
}).ToList();
更多信息
- 将Select LINQ查询运算符与索引一起使用