我不确定你是否真的需要动态 linq 来做你想做的事。根据我的经验,如果您使用 C# .NET 4.5 或 4.0,只要常规 System.Linq 应该处理查找位置索引,并且元素应该可以正常工作。这是一个应该可以正常工作的简单控制台应用程序:
using System;
using System.Collections.Generic;
using System.Linq;
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
public static List<User> Users;
static void Main(string[] args)
{
Users = new List<User>
{
new User
{
FirstName = "Brett",
LastName = "M"
},
new User
{
FirstName = "John",
LastName = "Doe"
},
new User
{
FirstName = "Sam",
LastName = "Dilat"
}
};
Console.WriteLine("Should work as long as object is defined and instantiated");
Console.WriteLine(Users.ElementAt(1).FirstName);
Console.WriteLine("\nIterate Through List with Linq\n I use a string you can add to another list or whatever\n\n");
string s = "";
Users.ForEach(n => s += "Position: " + Users.IndexOf(n) + " " + n.LastName + Environment.NewLine);
Console.WriteLine(s);
Console.ReadLine();
}
}
如果您只想通过该集合的属性在集合中查找特定对象,则可以使用“FindIndex”方法:
Console.WriteLine("Index of Dilat: " + Users.FindIndex(n => n.LastName.Equals("Dilat")));
编辑 9-27-13 用于拆分字符串。
如果您想获取一个字符串并将其拆分为一个很好的可启用列表以进行迭代,您也可以这样做。您只需要找到分隔符。如果你没有,你将不得不使用一些更复杂的正则表达式魔法。
保持一切不变,但替换我的 MAIN 方法:
string split = "Brett,Same,John,Frank";
List<string> stringList = split.Split(',').ToList();
string s = "";
stringList.ForEach(n => s += n + Environment.NewLine);
s += "\n\nFor Observing Element at\n";
s += "John is at: " + stringList.FindIndex(n => n.Equals("John"));
s += "\n\nGetting Poco Objects assigned and listed\n";
var list = stringList.Select(u => new User
{
FirstName = u,
LastName = "Something"
}).ToList();
list.ForEach(n => s += "User: " + n.FirstName + " " + n.LastName + "At: " + list.IndexOf(n) + Environment.NewLine);