how can i add these 3 records to the object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortedListDemo
{
class Sorted_List
{
int id, marks;
string name;
public Sorted_List(int id, string name, int marks)
{
this.id = id;
this.name = name;
this.marks = marks;
}
public override string ToString()
{
return String.Format("id: {0,-5} name: {1,-5} marks : { 2}",id,name,marks);
}
}
class SortedList1
{
static void Main(string[] args)
{
SortedList<Sorted_List, int> sobj = new SortedList<Sorted_List, int>();
Sorted_List s = new Sorted_List(1, "hello", 34);
Sorted_List s1 = new Sorted_List(20, "world", 32);
Sorted_List s2 = new Sorted_List(0, "hai", 98);
//here not adding the records,giving string format exception
sobj.Add(s, 3);
sobj.Add(s1, 0);
sobj.Add(s2, 1);
foreach (KeyValuePair<Sorted_List, int> s4 in sobj)
{
Console.WriteLine(s4);
}
}
}
}
Nilanka DharmadasaPosted Dec 24, 2009, 2:42 AM
Change your class as follows.
class Sorted_List : IComparable
{
int id, marks;
string name;
public Sorted_List(int id, string name, int marks)
{
this.id = id;
this.name = name;
this.marks = marks;
}
public override string ToString()
{
return String.Format("id: {0,-5} name: {1,-5} marks : { 2}", id, name, marks);
}
public int CompareTo(object obj)
{
if (obj is Sorted_List)
{
Sorted_List p2 = (Sorted_List)obj;
return id.CompareTo(p2.id);
//Will be sorted by ID property of the sorted_list object.
//You can sort by name if you want.
}
else
throw new ArgumentException("Object is not of type Sorted_List.");
}
}