Category Archives: C#

C# – Sorting a List of Objects

// Use IComparable Interface and implement CompareTo method. Uses the standard -1, 0, 1

class MyObject: IComparable
{
    public string Label;

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;
        MyObject otherObject = obj as MyObject;
        if (otherObject != null)
            return this.Label.CompareTo(otherObject.Label);
        else
            throw new ArgumentException("Object is not a MyObject");
    }
}

List myObjects = createMyObjects(); // defined elsewhere
myObjects.sort();

LINQ Multi-Dimensional GroupBy

var transactions = new[] {
  new { Customer = "Andy", Amount = 28, Year = 2012, Month = "Jan" },
  new { Customer = "Bob", Amount = 101, Year = 2012, Month = "Jan" },
  new { Customer = "Claire", Amount = 28, Year = 2012, Month = "Feb" },
  new { Customer = "Andy", Amount = 28, Year = 2013, Month = "Jan" },
  new { Customer = "Claire", Amount = 28, Year = 2013, Month = "Jan" },
  new { Customer = "Claire", Amount = 73, Year = 2013, Month = "Feb" },
};

var res = transactions
  .GroupBy(t => new { t.Year, t.Month });

foreach (var g in res)
  Console.WriteLine("{0} => {1}", g.Key, g.Sum(t => t.Amount));

Outputs:
{ Year = 2012, Month = Jan } => 129
{ Year = 2012, Month = Feb } => 28
{ Year = 2013, Month = Jan } => 56
{ Year = 2013, Month = Feb } => 73

C# read CSV using LINQ

class User
{
  public string RecordId;
  public string Email;
  public string FirstName;
  public string LastName;
  public string IsMember;
  public string IsFullSubscriber;
  public string MailingList;
  public string Activated;
  public string Source;
  public string CreatedAt;      
}


List<User> ReadCSV(string filename)
{
  return File.ReadLines(filename)
    .Skip(1)
    .Where(s => s != "")
    .Select(s => s.Split(new[] { ',' }))
    .Select(a => new User
    {
      RecordId = a[0],
      Email = a[1],
      FirstName = a[2],
      LastName = a[3],
      IsMember = a[4],
      IsFullSubscriber = a[5],
      MailingList = a[6],
      Activated = a[7],
      Source = a[8],
      CreatedAt = a[9]
    })
    .ToList();
}

C# write to TSV / Tab file

Using System.IO;

TextWriter writer = new StreamWriter(@"C:\test.tab");
writer.WriteLine(String.Join("\t", new[] { "abc", "def" }));
writer.WriteLine(String.Join("\t", new[] { "123", "456" }));
writer.Close();

Important thing to note is that it's "\t" not @"\t"

How to get C# LINQ working in Visual Studio 2010 and SQL Server Express

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _130122_LINQTest4
{
  class Program
  {
    static void Main(string[] args)
    {

      // Creates a new database in SQL Server Management Studio
      // Created a table called Skateboards

      // Added a new Data Connection from the Database Explorer tab

      // Top Menu > Project > Add New Item > Linq to SQL classes
      // Said 'Yes' to copy local copy to output path -- hence why the .mdf
      // is now in the Solution Explorer

      // From the Database Explorer, dragged my tables into the .dbml viewer
      // what this does is it creates the entity code so I can use LINQ

      using (var db = new DataClasses1DataContext())
      {
        var skateboards = from r in db.Skateboards select r;
      }
    }
  }
}