0

我有这种结构:

public class Record
{
    public int Id { get; set; }
    public List <Field> Fields;
}

public class Field
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

所以这是我的自定义类,用字段表示记录。

现在,我有很多记录List<Record> Records,我希望能够通过字段值(从Field.Value)对记录进行排序。

因为 Field 类包含 Id 属性,所以我有一个列表 ( List<int> SortByFieldIds),它显示了我必须使用哪些字段进行排序。

我的问题是我不知道如何处理它。我不知道如何编写一个方法来获取List<Record> RecordsToSortList<int> SortByFieldIds返回我的记录的排序列表。请帮帮我。

4

3 回答 3

0

您可以使用 LINQ 对列表进行排序。就像是:

List<Record> list = new List<Record>();
List<Record> SortByFieldIds = list.OrderBy(r => r.Fields.Select(a => a.Id)).ToList();

编辑

如果要先搜索 ID,然后根据值排序,请尝试:

int yourFieldID = 0;//this will hold your Field.ID
List<Record> sortByFieldId = list.OrderBy(
                                          r => r.Fields.Where(
                                          a => a.Id == yourFieldID
                                          ).FirstOrDefault().Value).ToList();

结束编辑

根据 ID 对记录列表进行排序

List<Record> sortByRecordId = list.OrderBy(r => r.Id).ToList();

记得包括

using System.Linq;
于 2012-07-06T05:46:23.177 回答
0

既然你提到你有一个List<int>ID,我想你想根据这些 ID 对List<Field>& 最后根据 ID 对字段进行Records排序IDField

例如,如果有 2 条记录

record 1 has 3 fields with IDs (1,2,3)
record 2 had 4 fields with IDs (4,3,6,2)

现在,如果List<int>有值6,2,3,您希望使用 ID 为 6、2、3 的字段返回记录,并且需要为每条记录对字段进行排序。

因此,对于示例案例,您的结果将是

record 1 has 3 fields with IDs (2,3)
record 2 had 4 fields with IDS (2,3,6)

如果这是您所追求的,那么这里是一个实际示例的代码

        List<Field> fields1 = new List<Field>();
        fields1.Add(new Field() { Id = 1, Name = "ONE", Value = "one" });
        fields1.Add(new Field() { Id = 2, Name = "TWO", Value = "two" });
        fields1.Add(new Field() { Id = 3, Name = "THREE", Value = "three" });

        List<Field> fields2 = new List<Field>();
        fields2.Add(new Field() { Id = 4, Name = "FOUR", Value = "four" });            
        fields2.Add(new Field() { Id = 3, Name = "THREE", Value = "three" });
        fields2.Add(new Field() { Id = 6, Name = "SIX", Value = "six" });
        fields2.Add(new Field() { Id = 2, Name = "TWO", Value = "two" });

        records.Add(new Record() { Id = 1, Fields = fields1 });
        records.Add(new Record() { Id = 2, Fields = fields2 });

        //You did mention that you already have this 
        List<int> SortByFieldIds = new List<int>();
        SortByFieldIds.AddRange(new List<int> { 6, 2, 3 });


        //before foreach loop records will have 2 records (record1 with fields 1,2,3 and record2 with fields 4,3,6,2)

        foreach (Record r in records)
        {
            r.Fields = r.Fields.Where(f => SortByFieldIds.Contains(f.Id)).OrderBy(f => f.Id).ToList();
        }

        //after foreach loop records will have 2 records (record1 with fields 2,3 and record2 with fields 2,3,6)
于 2012-07-06T11:04:00.400 回答
0

您可以使用 LINQOrderBy

您可以在类级别制作 SortByFieldIds,并将IComparer传递给 OrderBy

于 2012-07-06T05:47:10.480 回答