0
我的程序創建一個列表,用Person
對象填充它,並嘗試查找與列表中第一個對象具有相同名稱的下一個對象的索引。知道特定索引的位置,程序可以將原始列表分成兩個不同的列表。但是,出於某種原因,當我期待它返回5的值時,LINQ表達式對於splitLocation
返回零。顯然,我在做LINQ表達錯誤,或者我不理解我應該如何使用FindIndex
。這裏是我的代碼:爲什麼我的LINQ表達式中的FindIndex不起作用?
using System.Collections.Generic;
using System.Linq;
namespace NeedleInHaystack
{
class Program
{
static void Main(string[] args)
{
// create the 'haystack'
var people = new List<Person>();
var person1 = new Person("Frank");
var person2 = new Person("Jules");
var person3 = new Person("Mark");
var person4 = new Person("Allan");
var person5 = new Person("Frank");
var person6 = new Person("Greg");
var person7 = new Person("Tim");
people.Add(person1);
people.Add(person2);
people.Add(person3);
people.Add(person4);
people.Add(person5);
people.Add(person6);
people.Add(person7);
// here's the 'needle'
var needle = people[0].Name;
var listA = new List<Person>();
var listB = new List<Person>();
// find the needle in the haystack
var splitLocation = people.FindIndex(person => person.Name.Equals(needle));
listA = people.Take(splitLocation).ToList();
listB = people.Skip(splitLocation).ToList();
}
}
public class Person
{
public Person(string name)
{
Name = name;
}
public string Name { get; set; }
}
}
非常感謝!我不知道FirstIndex的重載會讓我指定一個起始索引。我甚至沒有想到要看。我非常感謝你的幫助! – Kevin