我有以下字符串列表{{a“,” b“,” c“,” d“,” e“}。我如何像这样使用LINQ获得长度为3的子列表:
{"a","b","c"}
{"b","c","d"}
{"c","d","e"}
我不是在寻找每种组合
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;
我不是在寻找类似的东西
{"a","b","c"}
{"a","b","d"}
{"a","b","e"}
.............
{"d","a","b"}
{"d","a","c"}
{"d","a","e"} and so on
学生班
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;
}
}
答案 0 :(得分:4)
您可以使用Select
的重载,它将重载当前元素的索引作为选择器的附加参数,并像这样使用它:
var triplets = sortedStudents.Take(list.Count - 2)
.Select((x, i) => new { S1 = x, S2 = list[i+1], S3 = list[i+2] });
答案 1 :(得分:2)
这是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));
答案 2 :(得分:0)
只需循环数组中的字符串即可:
public IEnumerable<IEnumerable<string>> GetTriples(string[] myArray)
{
for (int i = 0; i < myArray.Length - 2; i++)
{
yield return myArray.Skip(i).Take(3);
}
}
此代码循环遍历数组中的每个字符串,并获取接下来的两个字符串。
答案 3 :(得分:0)
假设(因为您没有完整的代码示例)您想要按照它们出现的顺序从集合中取出三倍的项目,则可以结合使用Skip
和{{1 }}为您提供代表三元组的子集。
Take