Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ获取表中的位置_C#_Linq - Fatal编程技术网

C# 使用LINQ获取表中的位置

C# 使用LINQ获取表中的位置,c#,linq,C#,Linq,我有带列的桌面播放器:ID Name Points 使用LINQ获得按点数排序的玩家位置的最有效方法是什么?任何解决方案都至少需要对所有元素进行一次迭代,但以下内容就足够了: var ordered = players.OrderByDescending(p => p.Points).ToList(); 这将在一次过程中对元素进行排序,然后将结果存储在列表中,以保留排序,而无需再次“排序”: int position = ordered.IndexOf(player); 您的deman

我有带列的桌面播放器:ID Name Points


使用LINQ获得按点数排序的玩家位置的最有效方法是什么?

任何解决方案都至少需要对所有元素进行一次迭代,但以下内容就足够了:

var ordered = players.OrderByDescending(p => p.Points).ToList();
这将在一次过程中对元素进行排序,然后将结果存储在列表中,以保留排序,而无需再次“排序”:

int position = ordered.IndexOf(player);

您的demande是单个linq查询,但这是一种方法:

int pos = 0;

foreach(var item in Players.OrderByDescending(u =>u.Points).ToList())
{
  pos++;
  if (item.Name == yourPlayerName)
  break;
} 
return pos;

另一个获取位置的选项(类似于Akrem,但不手动迭代集合)


您是否能够获得按点排序的结果集?在那之后,您是在问如何获取一条记录的序号,您知道该记录的ID吗?db.Players.OrderByDescending(u=>u.Points).ToList();其中db是linq数据上下文您是指表在列表中的位置吗?还是说ID=位置?
    [TestMethod]
    public void TestMethod()
    {
        var table = new[] 
        {
            new{ Id = 1, Name = "Paul", Points = 10},
            new{ Id = 2, Name = "Ringo", Points = 2},
            new{ Id = 3, Name = "George", Points = 30},
            new{ Id = 4, Name = "John", Points = 5}
        };
        int position = table.OrderByDescending(x => x.Points).TakeWhile(x => x.Name != "Paul").Count() + 1;
        Assert.AreEqual(2, position);
    }