gpt4 book ai didi

c# - 使用 Linq 将包含基元数据的对象列表分组为新的对象分组列表

转载 作者:行者123 更新时间:2023-12-03 21:15:23 25 4
gpt4 key购买 nike

我有一个包含不同原始数据类型的对象列表:

List<object> list = new List<object>() { 
3, "cat", 4.1, 'a', 5, "dog", "horse", 9.1, 'd', 1
};

我希望能够在上面的列表上运行 Linq 查询,该查询按数据类型和顺序将所有元素分组为(字符串、整数、 double 、字符)(如果这有意义?)。就像是:
list = { "cat","dog", "horse", 3, 5, 1, 4.1, 9.1, 'a', 'd' }

我试过

Using Linq to group a list of objects into a new grouped list of list of objects

代码
lst
.GroupBy(x => x.GetType())
.Select(grp => grp.ToList())
.ToList()
.ForEach(group => group.ForEach(item => Console.WriteLine(item)));

有效,但没有提供所需的输出。

输出
 { 3, 5, 1, "cat","dog", "horse",4.1, 9.1, 'a', 'd' }

最佳答案

如果问题是输出中类型的顺序,您可以使用自定义 IComparer类(class)和Sort你列出来。

基本原理是您可以将类型映射到整数分数,然后返回分数之间的比较。

documentation .

( dotnetFiddle )

public class StringThenIntThenDoubleThenChar  : Comparer<object> 
{
public override int Compare(object x, object y)
{
return GetTypeScore(x).CompareTo(GetTypeScore(y));
}

private int GetTypeScore(object o)
{
var type = o.GetType();
if (type == typeof(string)) return 0;
else if (type == typeof(int)) return 1;
else if (type == typeof(double)) return 2;
else if (type == typeof(char)) return 3;
else return 4;

/* Or, if you are using C# 8 :
return o.GetType() switch
{
Type t when t == typeof(string) => 0,
Type t when t == typeof(int) => 1,
Type t when t == typeof(double) => 2,
Type t when t == typeof(char) => 3,
_ => 4
};
*/
}
}

像这样使用它:
        List<object> list = new List<object>() { 3, "cat", 4.1, 'a', 5, "dog", "horse", 9.1, 'd', 1 };

list.Sort(new StringThenIntThenDoubleThenChar());
list.ForEach(x => Console.WriteLine(x));

相对于已经给出的更简单的解决方案(按类型名称排序)的优势在于您可以根据需要对其进行自定义。

您还可以细化比较器,例如如果分数相等,则可以使用它们的默认比较顺序进行比较(以便 stringint 等分别在它们之间排序)。

关于c# - 使用 Linq 将包含基元数据的对象列表分组为新的对象分组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61285958/

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