K
kndg
Hi all,
Suppose I have a Customer class defined below,
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Customer(int id, string name, string address)
{
Id = id;
Name = name;
Address = address;
}
}
and a list of customers,
var customers = new List<Customer>();
customers.Add(new Customer(1, "A", "A avenue"));
customers.Add(new Customer(2, "R", "R road"));
customers.Add(new Customer(3, "S", "S street"));
List is indexed using numbers, so if I want to access the list using
customer's name I have to resort using Dictionary<string, Customer>.
But, what if I want to access the list using both number and customer name?
I could just inherit a List and make a collection class like below,
public class CustomerCollection : List<Customer>
{
public Customer this[string customerName]
{
get
{
foreach (var item in this)
{
if (item.Name == customerName) return item;
}
return null;
}
}
}
var customers2 = new CustomerCollection();
customers2.AddRange(customers);
Console.WriteLine(customers[1].Address);
Console.WriteLine(customers["R"].Address);
But, I'm wondering if it possible to just extend the indexer like this,
internal static class MyExtension
{
public static Customer this[this List<Customer> list, string
customerName]
{
get
{
foreach (var item in list)
{
if (item.Name == customerName) return item;
}
return null;
}
}
}
Yeah, the above won't compile, but I think it would be cool.
Regards.
Suppose I have a Customer class defined below,
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Customer(int id, string name, string address)
{
Id = id;
Name = name;
Address = address;
}
}
and a list of customers,
var customers = new List<Customer>();
customers.Add(new Customer(1, "A", "A avenue"));
customers.Add(new Customer(2, "R", "R road"));
customers.Add(new Customer(3, "S", "S street"));
List is indexed using numbers, so if I want to access the list using
customer's name I have to resort using Dictionary<string, Customer>.
But, what if I want to access the list using both number and customer name?
I could just inherit a List and make a collection class like below,
public class CustomerCollection : List<Customer>
{
public Customer this[string customerName]
{
get
{
foreach (var item in this)
{
if (item.Name == customerName) return item;
}
return null;
}
}
}
var customers2 = new CustomerCollection();
customers2.AddRange(customers);
Console.WriteLine(customers[1].Address);
Console.WriteLine(customers["R"].Address);
But, I'm wondering if it possible to just extend the indexer like this,
internal static class MyExtension
{
public static Customer this[this List<Customer> list, string
customerName]
{
get
{
foreach (var item in list)
{
if (item.Name == customerName) return item;
}
return null;
}
}
}
Yeah, the above won't compile, but I think it would be cool.
Regards.