gpt4 book ai didi

c# - LINQ 按名称选择属性

转载 作者:太空狗 更新时间:2023-10-29 21:01:01 26 4
gpt4 key购买 nike

<分区>

我试图在 LINQ select 语句中使用变量。

这是我现在正在做的一个例子。

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();
}

我认为 refection 可能是 DeadEnd/red herring,但我想我还是会展示我的作品。

注意示例代码实际上已简化,用于填充 datalist通过 AJAX 创建自动完成体验。该对象有 20 多个属性,我可以通过编写 20 多个方法来完成,但我觉得应该有一个 DRY 方法来完成它。同样制作这个方法也会清理我的 Controller Action 。

问题:

鉴于代码的第一部分,有没有一种方法可以将这些类似的方法抽象为一个方法,购买将一些对象传递到 select 语句中???

感谢您的宝贵时间。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com