我有两种类型:
class Person
{
public string Name {get;set;}
public string Car {get;set;}
}
和第二种:
class Employee
{
public string Name {get;set;}
public string Salary {get;set;}
}
属性的 名称 相同(在两种类型上)。
我还得到了列表:
List<Person> _ListPerson = new List<Person>
List<Employee> _ListEmployee = new List<Employee>();
我在哪里添加了一些项目:
_ListPerson.Add( new Person { Name = "Jora" , Car = "BMW" };
_ListPerson.Add( new Person { Name = "Andrew" , Car = "Audi" };
_ListPerson.Add( new Person { Name = "Vasya" , Car = "Jiguli" };
_ListPerson.Add( new Person { Name = "Vasya" , Car = "Mercedes" };
_ListPerson.Add( new Person { Name = "Andy" , Car = "Renault" };
_ListEmployee.Add(new Employee { Name = "Vasya", Salary = "1000$"};
_ListEmployee.Add(new Employee { Name = "Andy", Salary = "200$"};
_ListEmployee.Add(new Employee { Name = "Andrew", Salary = "5000$"};
_ListEmployee.Add(new Employee { Name = "Jora", Salary = "100$"};
出于某种原因,我需要统一这些类型:
List<Object> People = New List<Object>();
People.AddRange(_ListPerson);
People.AddRange(_ListEmployee);
那么我如何通过 lambda 表达式对这些人进行排序?
目前我正在做这样的事情:
var _TEMP = _List.OfType<Person>().GroupBy(x => x.Name);.... //etc ,how i can use order by for these two types? Because oftype works only for one type.
最佳答案
最简单的方法是 Person
和 Employee
共享一些公共(public)基类或实现一个公共(public)接口(interface)。例如:
public interface IName
{
string Name { get; }
}
class Person : IName
{
public string Name { get; set; }
public string Car { get; set; }
}
class Employee : IName
{
public string Name { get; set;}
public string Salary { get; set;}
}
然后不是创建 List<object>
并使用 OfType
,您可以使用这种常见类型创建您的列表:
var people = new List<IName>();
people.AddRange(_ListPerson);
people.AddRange(_ListEmployee);
和组:
var grouped = people.GroupBy(x => x.Name);
尽管您提到要排序,但实际上可以使用 OrderBy
来实现或 OrderByDescending
:
var sorted = people.OrderBy(x => x.Name);
关于c# - 通过 Lambda 表达式对 List<Object> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30574475/