我有这种结构:
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> RecordsToSort
和List<int> SortByFieldIds
的方法并返回我的记录的排序列表。请帮帮我。
答案 0 :(得分: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;
答案 1 :(得分:0)
答案 2 :(得分:0)
由于您提到您有List<int>
个ID,我认为您想要进行过滤
基于List<Field>
Records
ID
属性Field
record 1 has 3 fields with IDs (1,2,3)
record 2 had 4 fields with IDs (4,3,6,2)
的ID
&安培;最后根据ID对字段进行排序。
例如,如果有2条记录
List<int>
现在,如果6,2,3
的值为record 1 has 3 fields with IDs (2,3)
record 2 had 4 fields with IDS (2,3,6)
,则您希望使用ID为6,2,3的字段返回记录,并且需要为每条记录对字段进行排序。
因此,对于示例案例,您的结果将是
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)
如果这是您所追求的那个,那么这里是实际示例的代码
{{1}}