创建从LINQ的新对象的新属性 [英] create new property in new object from linq

查看:141
本文介绍了创建从LINQ的新对象的新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我做一个LINQ到SQL查询和结果来作为一个IEnumerable。从这个名单,我创造​​了返回的每个结果的新对象。我使用已经在存储过程返回的,我希望的顺序中的对象。我们有一个领导委员会,结果在查询后降序排列。部分我有问题,就是我想补充的排名进入一个新的属性,在新的对象。

so I am doing a linq-to-sql query and the results come as an IEnumerable. From this list I am creating a new object for each result that is returned. The stored procedure that I am using already is returning the objects in the order that I want. We have a leader board and the results are in descending order after the query. the part I am having problems with is I want to add the ranking into a new property in the new object.

说我有这个code

 var usersSummary = Context.[myStoredProcedure]
            return usersSummary.Select(x => new [myObject]
            {
                UserId = x.UserID,
                FirstName = x.FirstName,
                LastName = x.LastName,
                TotalPoints = x.TotalPoints,
                LeaderBoardRank = //this part here
                Email = x.Email,
                CreatedDate = x.CreatedDate
            }).OrderByDescending(x => x.TotalPoints).ToList();

我想 LeaderBoardRank 将自己的排名。它们已经在排序排名顺序,所以第一个对象将是1,接下来的2,依此类推。因为这不是一个普通的C#循环即时通讯不太清楚如何来填补这一属性与排名。

I would like the LeaderBoardRank to be their ranking. They are already sorted in ranking order , so the first object would be 1 , the next 2 , and so on. Since this is not a normal c# loop im not too sure how to fill this property with the ranking.

推荐答案

如果通过新财产你的意思是 LeaderBoardRank ID不是一个性质 myObject的则没有,你不能这样做。你要么需要定义另一个类(可能扩展为MyObject )或使用匿名类型,无论是与附加属性或具有两个属性 - 秩和对象

If by "new property" you mean that LeaderBoardRank id NOT a property of myObject then no, you can't do that. You either need to define another class (possibly that extends MyObject) or use an anonymous type, either with that additional property or with two properties - the rank and the object.

如果 LeaderBoardRank 的一个属性,您要添加的排序结果的排名,你可以这样来做:

If LeaderBoardRank is already a property and you want to add the rank of the sorted result, you can do it this way:

var usersSummary = Context.[myStoredProcedure];

return usersSummary.OrderByDescending(x => x.TotalPoints)
                   .Select((x, i) => new [myObject]
{
    UserId = x.UserID,
    FirstName = x.FirstName,
    LastName = x.LastName,
    TotalPoints = x.TotalPoints,
    LeaderBoardRank = i
    Email = x.Email,
    CreatedDate = x.CreatedDate
}).ToList();

请注意,这不能解释的联系 - 这意味着如果两个用户具有相同的总积分,他们不会有相同的等级。

Note that this does NOT account for ties - meaning if two users have the same total points they will not have the same rank.

这篇关于创建从LINQ的新对象的新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆