C# 使用LINQ从字符串列表中提取重叠的子字符串
我有以下字符串列表{“a”、“b”、“c”、“d”、“e”}。如何使用LINQ获得长度为3的子列表,如下所示:C# 使用LINQ从字符串列表中提取重叠的子字符串,c#,.net,list,linq,C#,.net,List,Linq,我有以下字符串列表{“a”、“b”、“c”、“d”、“e”}。如何使用LINQ获得长度为3的子列表,如下所示: {"a","b","c"} {"b","c","d"} {"c","d","e"} var triplets = sortedStudents.Take(list.Count - 2) .Select((x, i) => new { S1 = x, S2 = list[i+1], S3 = list[i+2] }); 我不是在寻找每个组合 var list = st
{"a","b","c"}
{"b","c","d"}
{"c","d","e"}
var triplets = sortedStudents.Take(list.Count - 2)
.Select((x, i) => new { S1 = x, S2 = list[i+1], S3 = list[i+2] });
我不是在寻找每个组合
var list = students.OrderBy(student => student.LastName)
.Select(student => student);
List<Student> sortedStudents = list.ToList();
var triplets = from x in sortedStudents
from y in sortedStudents
from z in sortedStudents
select new { x, y, z};
StudentListBox.ItemsSource = triplets;
学生班
class Student
{
public Student()
{
}
public String FirstName
{
get;
set;
}
public String LastName
{
get;
set;
}
public DateTime Birthday
{
get;
set;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
这里有一种使用Linq的方法-
。Take(3)
定义长度为3
string[] input = { "a", "b", "c", "d", "e" };
var result = Enumerable.Range(0, input.Length - 2).Select(x => input.Skip(x).Take(3));
只需循环数组中的字符串:
public IEnumerable<IEnumerable<string>> GetTriples(string[] myArray)
{
for (int i = 0; i < myArray.Length - 2; i++)
{
yield return myArray.Skip(i).Take(3);
}
}
public IEnumerable GetTriples(字符串[]myArray)
{
for(int i=0;i
此代码循环数组中的每个字符串,并获取接下来的两个字符串。您可以使用超负荷的
Select
,将当前元素的索引作为选择器的额外参数,并按如下方式使用:
{"a","b","c"}
{"b","c","d"}
{"c","d","e"}
var triplets = sortedStudents.Take(list.Count - 2)
.Select((x, i) => new { S1 = x, S2 = list[i+1], S3 = list[i+2] });
假设(因为您没有完整的代码示例),您希望按照项目出现的顺序从集合中提取项目的三元组,您可以使用Skip
和take
的组合来提供表示三元组的子集
var triplets = new List<IEnumerable<Student>>();
for(int i = 0; i < (sortedStudents.Count - 2); i++)
{
triplets.Add(sortedStudents.Skip(i).Take(3));
}
var triplets=newlist();
对于(int i=0;i<(sortedStudents.Count-2);i++)
{
三胞胎。添加(分类学生。跳过(i)。取(3));
}
除了这篇文章之外,您还有其他方面的努力吗?您已经尝试了什么?我们没有做你应该做的,那就是思考。我尝试了很多方法,但是那些有效的方法,产生了所有的组合。用一些上下文代码和我的上一次尝试更新了帖子。你能在你的代码中包含学生的定义吗?当你说“我不是在寻找每个组合”时,你的确切意思是什么?谢谢你的帮助。我在提出一种基于起点的分组方法时遇到了问题,而这正是我所需要的。