排序列表<;T>;使用数组

本文关键字:数组 gt lt 排序 列表 | 更新日期: 2023-09-27 18:00:38

基本上我有一个包含所有项目的列表。然后我有一个字符串,其中包含我想从列表中获取的ID,为此,我将字符串拆分为Int数组,然后使用this和LINQ从列表中获取我想要的项目

像这样:

List<T> lstAllList = Model.getAllItems();
string stringIDs = "8,9,12,11,7";
int[] intArray = stringIDs.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
List<T> lstLimitedList = (from r in lstAllList where intArray.Contains(r.id) select r).ToList();

效果很好。

但这里的问题是,我希望以与ID字符串相同的方式对列表进行排序,即像本例中那样的8,9,12,11,7。但LINQ返回的列表默认情况下按id进行排序,因此返回的列表为7,8,9,11,12。

有没有办法防止它这样排序,或者有没有办法用我的int数组对新列表排序?

排序列表<;T>;使用数组

当然,只需按照数组中ID的索引进行排序:

string stringIDs = "8,9,12,11,7";
int[] intArray = stringIDs.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
var lstLimitedList = (
        from r in lstAllList 
        where intArray.Contains(r.id) 
        orderby Array.IndexOf(intArray, r.id)   // <--------
        select r).ToList();

简单地一次获取一个元素可能比尝试使用更快。(有人愿意计算O()成本吗?)

List<T> lstLimitedList = new List<T>();
foreach(int id in intArray)
{
    lstLimitedList.Add(lstAllList.Where(item => item.id = id));
}

如果你是一个LINQ狂,你也可以使用intArray.ForEach(),但这更容易阅读。)

尝试旋转查询。在单词rotate下,我的意思是从intArray开始并使用join。类似这样的东西:

List<T> lstLimitedList = (
from id in intArray 
join item in lstAllList on id equals item.Id 
select item).ToList();

Id使用LINQ提供的intersect扩展方法!

int[] array ={ 8,9,12,11,7} // or your result from your split on string;
List<int> array2 = new List<int> { 8,9,12,11,7 } // your model.GetAllItems;
// Call Intersect extension method.
var intersect = array.Intersect(array2);
// Write intersection to screen.
foreach (int value in intersect)
{
    Console.WriteLine(value); // Output: 8,9,12,11,7 
}

我的钻头清理器

停止过度使用LINQ家伙。在这种情况下,linq完全是小题大做。一个更简单、性能更好的解决方案如下:

string a = "8,9,12,11,7";
List<int> list = new List<int>();
string[] splitted = a.Split(',');
for (int i = 0; i < splitted.Length; i++)
{
    list.Add(int.Parse(splitted[i]));
}

哪个是单循环,没有排序等。