开发者

Single sorted c# list with different types?

开发者 https://www.devze.com 2023-01-11 00:48 出处:网络
Yes, I\'m new to c#! :) i\'m using .Net4 VS2010. I have Three classes each one is used to build a list of objects of that type. All three inherit form a base class.

Yes, I'm new to c#! :) i'm using .Net4 VS2010.

I have Three classes each one is used to build a list of objects of that type. All three inherit form a base class.

I want to combine the resulting three lists in to one and sort them on one of the base class elements.

Can this be done with lists of different types?

Simplified Example:

Each list is created

public List<TestOne> TestOne list;
public List<TestTwo> TestTwoList;
public List<object> BothLists;

Code to fill TestOne and TestTwo…

What/How do I combine both TestOne and TestTwo into BothLists and sort them on SeqNumber???

public class BaseClassTest 
{
    public string Loc { get; set; }  // loc
    // sequence number to order by will be assigned in the resulting class
    public int SeqNumber { get; set; } 
}

public class TestOne : BaseClassTest
{
    public int Number { get; set; } 
} 

public class TestTwo : BaseClassTest
{
    public 开发者_运维知识库string CatName { get; set; } 
} 


You should be able to do:

List<BaseClassTest> sorted = TestOneList.Cast<BaseClassTest>()
                    .Union(TestTwoList.Cast<BaseClassTest>())
                    .OrderBy(item => item.SeqNumber)
                    .ToList();

This will do your sort + union all at once.


"BothLists" should be a List<BaseClassTest>. That should let you sort on base class properties, using .OrderBy(x => x.SequenceNumber).

EDITED TO ADD:

Following up from comments, this should work to combine the lists:

BothLists = TestOneList.OfType<BaseClassList>().Concat().(TestTwoList.OfType<BaseClassList>()).ToList();

Generally, .OfType<>() is preferable to .Cast<>() because it simply filters based on type, rather than forcing a cast.


Given your example this is quite easy:

public List<BaseClassTest> BothLists;

Then you can sort:

BothLists.Sort((a, b) => a.SeqNumber.CompareTo(b.SeqNumber));  


If a class inherits from a base, it counts as the base class for most operations. Thus:

List<BaseClassTest> AllTests;

Should get you what you need.


Make TestOne and TestTwo implement the IComparable interface. See here. Then you can combine the lists into an ArrayList and use the Sort method.


List<BaseClassTest> list3 = new List<BaseClassTest>();
list3.AddRange(list1);
list3.AddRange(list2);
var sorted = list3.OrderBy(e => e.SequenceNum).ToList(); //if you really need a list back

This is all assuming you have Linq available. Of course if you do a Union statement might work also.

0

精彩评论

暂无评论...
验证码 换一张
取 消