c# - 内部列表中按字符串长度列出的实体的顺序列表
问题描述
有2个班:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Question> Questions { get; set; }
}
public class Question
{
public int Id { get; set; }
public string Type { get; set; }
public string Answer { get; set; }
}
一个由 X 名员工和 4 个问题组成的列表,每个员工都有,有没有办法通过问题答案对员工进行动态排序?就像我在我的反应应用程序中按“症状”表格中的升序排序按钮一样,它首先给我的员工对“症状”类型的问题给出“否”答案,然后是“是”,然后是“也许” ”。我无法弄清楚什么 LINQ 表达式甚至可以做到这一点。在我的脑海中,我有点想象我应该做什么,但我不能只写查询。
var list = new List<Employee>()
{
new Employee
{
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "Yes"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
},
new Employee
{
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "Yes"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
},
new Employee
{
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "Yes"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
}
};
朋友说要写个比较器,但是这里具体怎么用我不太明白
解决方案
1,您的“问题”类缺少“类型”属性。
但是在添加该属性代码后看起来没问题。2,当你添加测试数据时,让它们变得更好。您的数据已经排序,因为所有问题都有相同的答案,即“是”。
我稍微编辑了你的测试数据:
var list = new List<Employee>()
{
new Employee
{
FirstName = "John",
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "Yes"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
},
new Employee
{
FirstName = "Emma",
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "Maybe"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
},
new Employee
{
FirstName = "Bill",
Questions = new List<Question>()
{
new Question() {Type = "Symptoms", Answer = "No"},
new Question() {Type = "Travel", Answer = "No"},
new Question() {Type = "Contact", Answer = "Maybe"},
new Question() {Type = "Test", Answer = "Yes"}
}
}
};
之后我做了 lambda 表达式:
var orderedList = list.OrderByDescending(x => x.Questions.Where(q => q.Type == "Symptoms").FirstOrDefault().Answer
switch
{
"No" => 3,
"Yes" => 2,
"Maybe" => 1,
_ => 0
}).ToList();
结果是:
在位置 1. 是 Bill
On 位置 2. 是 John
On 位置 3. 是 Emma
如果我误解了你的问题,我很抱歉。
推荐阅读
- angular - 我怎样才能隐藏角度的插槽?
- sql - PySpark/Spark 相关标量子查询,按顺序排列
- node.js - 身份验证后写入 Firestore
- json - 用 jq 重新格式化 json - 将结果收集到数组中
- javascript - 如何分隔参数中的单词(discord.js)
- visual-studio - 使用 minGW 创建用于英特尔 Fortran 的静态库
- proxy - 防止 Nexus 提取被阻止的包元数据
- python - list.append() 函数的奇怪行为
- java - How can I create a method that evaluates two variables from main class?
- vue.js - 如何解决“代码丢失或不完整”?Vue 应用中的 Google Adsense