gpt4 book ai didi

c# - 按列表包含的对象的属性对自定义列表进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:33 25 4
gpt4 key购买 nike

我创建了一个不是 IEnumerable 的自定义列表类。因此,我不能使用 Enumerable.OrderBy

class MyList<T> 
{
class ListElement
{
public T content;
public ListElement next;
}
ListElement head;
}

在此之后,我将具有字符串属性的对象放入其中。我想按列表包含的对象的字符串属性对列表进行排序。

最佳答案

在这种情况下,最好只使用 IEnumerable,或者甚至更好,只从列表类派生...我将向您展示如何实现这两者。

public class MyList<T> : IEnumerable<T>
{
private List<T> itemCollection;

public MyList()
{
this.itemCollection = null;
}

public void Add(T item)
{
this.itemCollection.Add(item);
}


public IEnumerator<T> GetEnumerator()
{
foreach (T item in this.itemCollection)
{
yield return item;
}
}

/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}

或者最简单的...

public class MyList<T> : List<T>
{

}

关于c# - 按列表包含的对象的属性对自定义列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29864365/

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