如果需要过滤数组,就使用Where,用Select和SelectMany主要目的是对选择进行转换。
1、Where:
测试代码:
void TestWhere()
{
string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" };
var tokens = text.Where(s => { return s.StartsWith("Bur"); });
StringBuilder sb = new StringBuilder();
foreach (string line in tokens)
sb.Append(string.Format("{0}.", line));
Debug.Log("TestWhere" + sb);
//Burke slept late.Burning.
}
2、SelectMany:
测试代码
void TestSelectManay()
{
Debug.Log("TestSelectManay");
string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" };
StringBuilder sb = new StringBuilder();
var tokens2 = text.SelectMany(s => s.Split(' '));
foreach (string token in tokens2)
sb.Append(string.Format("{0}.", token));
Debug.Log("TestSelectManay" + sb);
//输出:Albert.was.here.Burke.slept.late.Connor.is.happy.Burning.
}
3、Select
测试代码:
void TestSelect()
{
Debug.Log("TestSelect");
string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" };
var tokens = text.Select(s => s.Split(' '));
StringBuilder sb = new StringBuilder();
foreach (string[] line in tokens)
foreach (string token in line)
sb.Append(string.Format("{0}.", token));
Debug.Log("TestSelect" + sb);
//输出:Albert.was.here.Burke.slept.late.Connor.is.happy.Burning.
}
4、Select与SelectMany的区别参考这段代码:
//From stackoverflow:
//SelectMany flattens queries that return lists of lists. For example
public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
}
IEnumerable<Person> people = new List<Person>();
// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);