如何两种类型的C#列表合并成一个? [英] How to combine two types of C# lists into one?
问题描述
我已经创建了两个名单说X'放大器; Y.这些两个列表是不同的类型。
(即列表< class_A> X
&放大器; 列表< class_B> Y
)。这两个列表
I have created two lists say X & Y. These two lists are of different types.
(ie List<class_A> X
& List<class_B> Y
).
值是不同的。但是,在这两个列表的的DateTime
字段。
Values in both these lists are different. But there is a DateTime
field in both these lists.
我需要根据这些列表进行排序日期
字段。
I need to sort these lists according to the date
field.
我有单独的函数来打印名单A和名单b的细节。
I have separate functions to print the details of list A and List B.
假设排序列表看起来像
- 从列表中的元组,
- 从名单b元组,
- 从列表中的元组,
- 从名单b元组,
- tuple from list A,
- tuple from list B,
- tuple from list A,
- tuple from list B,
我的目的是要遍历这个列表,并调用相应的函数来显示的细节。即如果元组是从列表的然后调用打印列表的的详细信息,反之亦然功能。
My purpose is to loop through this list and call the appropriate function to display the details. ie if the tuple is from list A then call the function for printing list A's details and vice versa.
推荐答案
您可以创建一个接口
来承载您的公共属性和功能,然后转换为这个接口后,加盟者名单,然后对它进行排序:
You can create an interface
to host your common properties and functions, then join those lists after casting to this interface and sort it then:
interface ICommon
{
DateTime DT { get; }
void Print();
}
class ClassA : ICommon
{
public DateTime DT { get; set; }
public void Print() { Console.WriteLine("A " + DT); }
}
class ClassB : ICommon
{
public DateTime DT { get; set; }
public void Print() { Console.WriteLine("B " + DT); }
}
public static void Main()
{
var listA = new List<ClassA> { new ClassA() { DT = DateTime.Now.AddDays(-1) }, new ClassA() { DT = DateTime.Now.AddDays(-3) }};
var listB = new List<ClassB> { new ClassB() { DT = DateTime.Now.AddDays(-2) }, new ClassB() { DT = DateTime.Now.AddDays(-4) }};
var orderedResult = listA.Cast<ICommon>()
.Concat(listB.Cast<ICommon>())
.OrderBy(q => q.DT);
//or possibly even better:
//var orderedResult = listA.Concat<ICommon>(listB).OrderBy(q => q.DT);
foreach (var obj in orderedResult)
obj.Print();
}
这篇关于如何两种类型的C#列表合并成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!