对不起,也许是菜鸟问题)但我只是想学习一些新东西。 我有一个包含许多字段的对象的数组 - 如何 使用 select 检查此对象的第一个字段是否等于某个字符串? (这个字段也是一个字符串,所以不需要类型操作)
请您参考如下方法:
考虑这个场景:
// Some data object
public class Data {
public string Name { get; set; }
public int Value { get; set; }
public Data(string name, int value)
{
this.Name = name;
this.Value = value;
}
}
// your array
Data[] array = new Data[]
{
new Data("John Smith", 123),
new Data("Jane Smith", 456),
new Data("Jess Smith", 789),
new Data("Josh Smith", 012)
}
array.Any(o => o.Name.Contains("Smith"));
// Returns true if any object's Name property contains "Smith"; otherwise, false.
array.Where(o => o.Name.StartsWith("J"));
// Returns an IEnumerable<Data> with all items in the original collection where Name starts with "J"
array.First(o => o.Name.EndsWith("Smith"));
// Returns the first Data item where the name ends with "Smith"
array.SingleOrDefault(o => o.Name == "John Smith");
// Returns the single element where the name is "John Smith".
// If the number of elements where the name is "John Smith"
// is greater than 1, this will throw an exception.
// If no elements are found, this` would return null.
// (SingleOrDefault is intended for selecting unique elements).
array.Select(o => new { FullName = o.Name, Age = o.Value });
// Projects your Data[] into an IEnumerable<{FullName, Value}>
// where {FullName, Value} is an anonymous type, Name projects to FullName and Value projects to Age.
