C#排序基于数值从另一个列表中的顺序列表(不同类别)数值、顺序、类别、不同

2023-09-04 11:28:24 作者:愿用一世繁华换你一时笑颜

我目前停留在一个问题,我有2个清单,我想根据从第一个列表中的值第二列表进行排序,下面是一个例子:

I'm currently stuck at a problem where I have 2 Lists, and I want to sort the second List according to a value from the first List, here is an example:

public class data
{
    public string Name{get; set;}
    public int ID{get; set}
}
public class dataToSort
{
    public int ID{get; set;}
    public string retrievedData{get; set}
    public string timeStamp{get; set}
}

因此​​,可以说我有2个List对象,一个用于数据,一个用于dataToSort,下面的内容:

So lets say I have 2 List objects, one for data and one for dataToSort, their contents below:

data: "Alpha", "80"           dataToSort: "21", "XA", "YA"
      "Beta", "47"                        "47", "XB", "YB"
      "Charlie", "153"                    "80", "XC", "YC"
      "Delta", "21"                       "153","XD", "YD"

所以,我想要做的就是让dataToSort相等于ID的数据,这样的顺序依次为:

So what I want to do is to make the order of dataToSort equal to the order of the IDs in data, like this:

dataToSort: "80", "XC", "YC"
            "47", "XB", "YB"
            "153","XD", "YD"
            "21", "XA", "YA"

我曾尝试使用Google的一种方式来排序这些,但所有的LINQ语法混淆了我,我必须因类的每个对象:(我能想到的唯一途径的差异问题是要有一个for循环得到一个列表的ID和指标做一些像冒泡排序,但它太麻烦了,也没有效率。帮助是极大的AP preciated!

I have tried googling for a way to Sort these but all the LINQ syntax confuses me and I have problems due to the difference in classes of each object :( The only way I can think of is to have a for loop to get the index of one List's ID and do something like a bubble sort, but its too much of a hassle and also inefficient. Help is greatly appreciated!

推荐答案

您可以加入的ID两个列表:

You can join the two lists on the IDs:

var query = from x in data
            join y in dataToSort on x.ID equals y.ID
            select y;

var result = query.ToList();

这保持了第一列表的顺序数据

This keeps the order of the first list data.

您还可以轻松地将二者结合起来的列表是这样的:

You can also easily combine the two lists this way:

var query = from x in data
            join y in dataToSort on x.ID equals y.ID
            select new
            {
                x.Name,
                x.ID,
                y.retrievedData,
                y.timeStamp,
            };

var result = query.ToList();