Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,762 questions

51,662 answers

573 users

How to sort a list of data classes by multiple columns in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

class Item
{
    public int A { get; set; }
    public int B { get; set; }
    public string Label { get; set; }

    public Item(int a, int b, string label) {
        A = a;
        B = b;
        Label = label;
    }

    public override string ToString() {
        return $"({A}, {B}, {Label})";
    }
}

class Program
{
    // Create dataset
    static List<Item> MakeData()
    {
        return new List<Item>
        {
            new Item(7, 2, "python"),
            new Item(8, 3, "c"),
            new Item(3, 5, "c++"),
            new Item(4, 1, "c#"),
            new Item(3, 2, "java"),
            new Item(7, 1, "go"),
            new Item(1, 2, "rust")
        };
    }

    // Sort by A then B
    static void SortData(List<Item> data) {
        data.Sort((x, y) =>
        {
            int cmp = x.A.CompareTo(y.A);
            if (cmp != 0) return cmp;
            return x.B.CompareTo(y.B);
        });
    }

    // Print all items
    static void PrintData(IEnumerable<Item> data) {
        foreach (var item in data)
            Console.WriteLine(item);
    }

    // Find first item by label
    static Item FindByLabel(IEnumerable<Item> data, string label) {
        return data.FirstOrDefault(i => i.Label == label);
    }

    // Filter by A
    static List<Item> FilterByA(IEnumerable<Item> data, int value) {
        return data.Where(i => i.A == value).ToList();
    }

    static void Main()
    {
        var data = MakeData();

        SortData(data);
        Console.WriteLine("Sorted data:");
        PrintData(data);

        Console.WriteLine();
        Console.WriteLine("Searching for 'java':");
        var found = FindByLabel(data, "java");
        if (found != null)
            Console.WriteLine(found);

        Console.WriteLine();
        Console.WriteLine("Filtering items where A == 7:");
        var filtered = FilterByA(data, 7);
        PrintData(filtered);
    }
}



/*
run:

Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)

Searching for 'java':
(3, 2, java)

Filtering items where A == 7:
(7, 1, go)
(7, 2, python)

*/

 



answered 1 day ago by avibootz

Related questions

...