【发布时间】:2017-12-12 21:01:36
【问题描述】:
我正在尝试在 LINQ 选择语句中使用变量。
这是我现在正在做的一个例子。
using System;
using System.Collections.Generic;
using System.Linq;
using Faker;
namespace ConsoleTesting
{
internal class Program
{
private static void Main(string[] args)
{
List<Person> listOfPersons = new List<Person>
{
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person()
};
var firstNames = Person.GetListOfAFirstNames(listOfPersons);
foreach (var item in listOfPersons)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.ReadKey();
}
public class Person
{
public string City { get; set; }
public string CountryName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person()
{
FirstName = NameFaker.Name();
LastName = NameFaker.LastName();
City = LocationFaker.City();
CountryName = LocationFaker.Country();
}
public static List<string> GetListOfAFirstNames(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfCities(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfCountries(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfLastNames(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
}
}
}
我有一些非常不干燥的代码,带有 GetListOf... 方法
我觉得我应该能够做这样的事情
public static List<string> GetListOfProperty(
IEnumerable<Person> listOfPersons, string property)
{
return listOfPersons.Select(x =>x.property).Distinct().OrderBy(x=> x).ToList();
}
但这不是有效的代码。我认为关键可能与创建函数有关
如果这就是答案,我该怎么做?
这是使用反射的第二次尝试但这也是不行的。
public static List<string> GetListOfProperty(IEnumerable<Person>
listOfPersons, string property)
{
Person person = new Person();
Type t = person.GetType();
PropertyInfo prop = t.GetProperty(property);
return listOfPersons.Select(prop).Distinct().OrderBy(x =>
x).ToList();
}
我认为反射可能是一个死胡同/红鲱鱼,但我想我还是会展示我的作品。
注意示例代码实际上已简化,用于通过 AJAX 填充 datalist 以创建自动完成体验。该对象有 20 多个属性,我可以通过编写 20 多个方法来完成,但我觉得应该有一个 DRY 方法来完成它。也使这种方法也可以清理我的控制器动作。
问题:
鉴于第一部分代码,有没有办法将这些类似的方法抽象为一个方法购买将一些对象传递给 select 语句???
感谢您的宝贵时间。
【问题讨论】:
-
除了显示代码之外,您能否用文字陈述您的问题?
-
DV 调用 GetProperty() 并在这里寻求帮助,甚至没有阅读 MSDN 文档。您的答案在文档中。
-
@Crowcoder 这只是另一个想要在给定属性名称的情况下选择属性值的人,作为字符串。
-
@Crowcoder 我添加了空白以更容易地查看问题。
标签: c# linq expression