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

标签 c# list linq

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

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/

相关文章:

python - 将列表的值插入到mysql Python的不同列中

python 使用字符串列表进行加密和解密

c# - 如何在不同类型的集合之间进行匹配?

c# - LINQ select 查询总是产生真值

c# - 使用 R.NET 从 c# 控制台应用程序中的 r 源文件调用函数

c# - 如何从 C# 中的二进制文件中检索整数值

Android 传感器 ListView

linq - NHibernate LINQ 查询抛出错误 "Could not resolve property"

c# - 无需用户交互即可登录 Google 服务

c# - 通过 JQuery 访问 Controller