首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在c#中的多个List <User>中拆分List <User>

在C#中,如果你有多个List<User>,并且想要将它们拆分成单个的List<User>,你可以使用以下方法:

  1. 使用List<T>.GetRange()方法:
代码语言:csharp
复制
List<User> list1 = new List<User>();
List<User> list2 = new List<User>();
List<User> list3 = new List<User>();

// 将原始列表拆分成多个列表
List<List<User>> splitLists = new List<List<User>> { list1, list2, list3 };

int startIndex = 0;
int batchSize = (int)Math.Ceiling((double)originalList.Count / splitLists.Count);

foreach (List<User> splitList in splitLists)
{
    int endIndex = Math.Min(startIndex + batchSize, originalList.Count);
    splitList.AddRange(originalList.GetRange(startIndex, endIndex - startIndex));
    startIndex = endIndex;
}
  1. 使用System.Collections.Concurrent.Partitioner类:
代码语言:csharp
复制
List<User> originalList = new List<User>();
List<User> list1 = new List<User>();
List<User> list2 = new List<User>();
List<User> list3 = new List<User>();

var partitioner = Partitioner.Create(originalList, true);

Parallel.ForEach(partitioner, (user) =>
{
    // 根据需要,可以在此处添加条件以将用户添加到特定列表中
    if (user.SomeProperty == "SomeValue")
    {
        list1.Add(user);
    }
    else if (user.SomeProperty == "AnotherValue")
    {
        list2.Add(user);
    }
    else
    {
        list3.Add(user);
    }
});

这两种方法都可以将一个List<User>拆分成多个List<User>GetRange()方法适用于将列表均匀地拆分成多个部分,而Partitioner类适用于根据特定条件将列表拆分成多个部分。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券