相关疑难解决方法(0)

如何按特定成员对对象列表进行排序?

假设我有一个Person对象列表:

class person
{
  int id;
  string FirstName;
  string LastName;
}
Run Code Online (Sandbox Code Playgroud)

我如何按LastName成员对此列表进行排序?

List<Person> myPeople = GetMyPeople();
myPeople.Sort(/* what goes here? */);
Run Code Online (Sandbox Code Playgroud)

.net c# sorting list

7
推荐指数
2
解决办法
6156
查看次数

Generic Linq OrderBy函数的问题

我在帖子中看到了以下函数,它允许用户使用通用表达式对数据进行排序:

public static IOrderedQueryable<T> OrderBy<T, TKey>(
  this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
  return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用这个函数时,我得到一个错误,说"找不到类型或命名空间名称"TKey'(你是否错过了使用指令或汇编引用?)".我在这里做了一些愚蠢的事情,但我可以弄明白了.

编辑:

在做了一些研究之后,我认为我的问题在于构建我传递给它的Expression.是否可以构建一个可以包含不同类型的表达式?假设我的数据集有一个字符串,一个int和一个bool,我想使用上面的泛型函数来排序任何项目.我该怎么做呢?

我现在有这个工作:

if (IsString)
{
   Expression<Func<T, string>> expString = ...;
   // call orderBy with expString
}
else if (IsInt)
{
   Expression<Func<T, int>> expInt;
   // call orderBy w/ expInt
}
:
Run Code Online (Sandbox Code Playgroud)

我想要的东西:

Expression<Func<T, {something generic!}>> exp;
if (IsString)
    exp = ...;
else if (IsInt)
    exp = ...;
:
// call orderBy with exp
Run Code Online (Sandbox Code Playgroud)

c# linq lambda

5
推荐指数
1
解决办法
7877
查看次数

获取List <Struct.int>的最小值

我有一个struct包含一些intbool成员的,我希望从列表中获得最低值(实际上是基于A*搜索的路径查找器).

基本上,我的对象看起来像这样:

    public struct Tile
    {
        public int id;
        public int x;
        public int y;
        public int cost;
        public bool walkable;
        public int distanceLeft;
        public int parentid;
    }
Run Code Online (Sandbox Code Playgroud)

我想得到距离最低的物品.列表声明如下:

        List<Structs.Tile> openList = new List<Structs.Tile>();
Run Code Online (Sandbox Code Playgroud)

并以这种方式分配值:

        while (pathFound == null)
        {
            foreach (Structs.Tile tile in map)
            {
                foreach (Structs.Tile tile1 in getSurroundingTiles(Current))
                {
                    if (tile1.x == tile.x && tile1.y == tile.y)
                    {
                        Structs.Tile curTile = tile1;
                        curTile.parentid = Current.id;
                        curTile.distanceLeft = (Math.Abs(tile.x - goalx) + …
Run Code Online (Sandbox Code Playgroud)

c# algorithm search a-star

-1
推荐指数
1
解决办法
1968
查看次数

标签 统计

c# ×3

.net ×1

a-star ×1

algorithm ×1

lambda ×1

linq ×1

list ×1

search ×1

sorting ×1