我有以下对象列表 - "Text1"、"Text2"、new UndefinedInfo("Undfined1")、new UndefinedInfo("Undfined2")、new UndefinedInfo("Undefine3")、"Text3"
我需要如下输出:
输出 //列表> 0 – 文本 1、文本 2 1 – 未定义 1、未定义 2、未定义 3 2 – 文本3
我设法编写了下面的函数,虽然很糟糕,但工作正常。有什么方法可以使用 LINQ 扩展 - TakeWhile 或 SkipWhile 或使用 Yield 来实现相同的目的。非常感谢任何帮助:
public static List<List<object>> PartitionByTypes(List<object> values)
{
List<List<object>> partitionedList = new List<List<object>>();
int j;
for (int i = 0; i < values.Count; i++)
{
j = i;
List<object> subList = new List<object>();
Type t = values[j].GetType();
do
{
subList.Add(values[j]);
j++;
if (j == values.Count)
{
break;
}
} while (values[j].GetType() == t);
partitionedList.Add(subList);
i = j - 1;
}
return partitionedList;
}
最佳答案
以下将使用 yield
执行您想要的操作。所以返回将是 IEnumerable<List<object>>
相反。
public static IEnumerable<List<object>> PartitionByTypes(List<object> values)
{
Type prevType = null;
List<object> cache = new List<object>();
foreach (var value in values)
{
if(prevType != null && value.GetType() != prevType)
{
yield return cache;
cache = new List<object>();
}
cache.Add(value);
prevType = value.GetType();
}
if(cache.Count > 0)
yield return cache;
}
或者,您可以使用以下 Linq 查询
public static IEnumerable<List<object>> PartitionByTypes(List<object> values)
{
int count = 0;
return values.Select((o, i) => new
{
Object = o,
Group = (i == 0 || o.GetType() == values[i - 1].GetType()) ? count : ++count
})
.GroupBy(x => x.Group)
.Select(g => g.Select(x => x.Object).ToList());
}
关于c# - 根据对象类型拆分对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573774/