![](/img/trans.png)
[英]How do i get “First Name” and “Last Name” from sharepoint list using c#
[英]Get list of students whose first name is before their last name alphabetically
因此,我列出了有名字和姓氏的学生。 如何使用LINQ查询以给定的方式过滤它们:它们的名字按字母顺序在姓氏之前?
我尝试了一些方法
var newStudents =
from s in students
where s.FirstName < s.LastName
select s;
我在这里面临的问题是无法以这种方式比较字符串。
学生还有一个包含成绩的int列表,以及另一个查询。 我需要提取所有2年级出现两次的学生。
例如,我需要选择一个成绩为{ 2, 3, 4, 5, 2 }
2、3、4、5、2 { 2, 3, 4, 5, 2 }
的学生,但忽略一个成绩为{ 2, 3, 4, 5, 6 }
2、3、4、5、6 { 2, 3, 4, 5, 2 }
的学生。
获取名字按字母顺序在姓前的学生列表
这将筛选出FirstName
在LastName
之前的学生,并按FirstName
,然后按LastName
顺序LastName
:
var newStudents = students
.Where(s => String.Compare(s.FirstName, s.LastName, StringComparison.Ordinal) < 0) // Filter students whose FirstName is before LastName
.OrderBy(s => s.FirstName) // Order by FirstName
.ThenBy(s => s.LastName); // If FirstNames are equal, then order by LastName
请注意,我正在使用区分大小写的StringComparison.Ordinal
。 您可能要改用StringComparison.OrdinalIgnoreCase
。
Darkbound的解决方案:
var newStudents =
from s in students
where s.FirstName.CompareTo(s.LastName) < 0
select s;
如果您使用的是Linq to Objects,则可以使用。
var filteredStudents =
from student in students
where String.Compare(s.FirstName, s.LastName, StringComparison.Ordinal) < 0
order by student.FirstName, student.LastName
select student;
我不知道它是否也适用于Linq to SQL。
最初有两个问题(我回滚了问题):
1)
如何使用LINQ查询以给定的方式过滤它们:它们的名字按字母顺序在姓氏之前?
2)
我需要选择一个
{ 2, 3, 4, 5, 2 }
2、3、4、5、2{ 2, 3, 4, 5, 2 }
年级的学生,但忽略一个{ 2, 3, 4, 5, 6 }
2、3、4、5、6{ 2, 3, 4, 5, 2 }
年级的学生。
关于这个问题。 1:作为其他成员,我建议使用OrderBy
和ThenBy
方法。 关于这个问题。 2:您必须对数据进行分组并获得出现两次的2级计数。 查看示例(使用LinqPad):
void Main()
{
List<Student> stu = new List<Student>(){
new Student("A", "B", new List<int>{ 2, 3, 4, 5, 2 }),
new Student("B", "A", new List<int>{ 2, 3, 4, 5, 6 }),
new Student("B", "A", new List<int>{ 2, 3, 4, 5, 4 })
};
var qry = stu
.OrderBy(s=>s.FirstName)
.ThenBy(s=>s.LastName)
.Where(s=>s.Grades.GroupBy(r=>r).Any(g=>g.Count(a=>a==2)>1));
//qry.Dump();
}
// Define other methods and classes here
public class Student
{
public Student(string sFName, string sLName, List<int> grades)
{
FirstName = sFName;
LastName = sLName;
Grades = grades;
}
public string FirstName{get;set;}
public string LastName{get;set;}
public List<int> Grades{get;set;}
}
结果:
FirstName LastName Grades
A B 2
3
4
5
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.