gpt4 book ai didi

c# - 根据特定条件将列表分为两个列表

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:33 25 4
gpt4 key购买 nike

另一个程序正在向我的程序传递对象列表。这些对象具有名为Title的属性,在此列表中,其中一个对象的标题与第一个对象的标题匹配。我想将此列表分为两个列表,将第二个对象具有与第一个相同的标题作为标志,以将其余对象写入另一个列表。我编写了一个小的示例程序,该程序指示我要完成的工作。我希望那里有人可以指出正确的方向。

static void Main(string[] args)
{
var names = new string[] {"Frank", "Jules", "Mark", "Allan", "Frank", "Greg", "Tim"};
var listA = new List<string>();
var listB = new List<string>();

foreach (var name in names)
{
// Add all names to listA, until name is the next "Frank".
// If name is the next "Frank" add name and all remaining
// names to listB.

// So, listA would contain "Frank", "Jules", "Mark", "Allan"
// listB would contain "Frank", "Greg", "Tim"
}
}

最佳答案

这就是我的处理方式(认为它使用LINQ,您可以不使用它):

void Main()
{
var names = new string[] {"Frank", "Jules", "Mark", "Allan", "Frank", "Greg", "Tim"};
var listA = new List<string>();
var listB = new List<string>();

// I'm not entirely sure where this comes from other than it's always
// the first element in the "names" list.
var needle = names[0]; // "Frank"

// this finds the location of the second "Frank"
var splitLocation = Array.IndexOf(names, needle, 1);

// here we grab the first elements (up to the splitLocation)
listA = names.Take(splitLocation).ToList();
// here we grab everything past the splitLocation
// (starting with the second "Frank")
listB = names.Skip(splitLocation).ToList();
}

关于c# - 根据特定条件将列表分为两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24172283/

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