C# – Anonymous Type Problem

by Svetlozar Angelov 12. January 2010 17:14

Anonymous types are great feature. You can code stuff like this:

static void Main(string[] args)
{
    var student = new { Name = "Svetlozar", LastName = "Angelov" };
    Console.WriteLine("Student - Name: {0}, Lastname: {1}",student.Name, student.LastName);
}

I believe most C# programmers love the way you can LINQ with anonymous types. Let’s see another example.

string[] Names = new string[] { "Svetlozar", "George", "Ivan" };
string[] LastNames = new string[] {"Angelov", "Dimitrov", "Ivanov" };
var students =
    from name in Names
    from lastname in LastNames
    select new
    {
        Name = name
        , Lastname = lastname
    };
foreach(var student in students)
    Console.WriteLine("{0} {1}",student.Name,student.Lastname);

Here comes the problem if we want to move the LINQ into a method.

public static IEnumerable<WHAT> GetNamesCombinations(string[] names, string[] lastnames)
{
    var students =
        from name in names
        from lastname in lastnames
        select new 
        {
            Name = name
            , Lastname = lastname
        };
    return students;
}

Here you have to create a type (Student for example) and to do it this way -

public static IEnumerable<Student> GetNamesCombinations(string[] names, string[] lastnames)
{
    var students =
        from name in names
        from lastname in lastnames
        select new Student 
        {
            Name = name
            , Lastname = lastname
        };
    return students;
}

but it is really annoying to create the Student class by hand. Visual Studio 2010 has a nice feature

image

and

image

Finally you end up with

class Student
{
    public string Name { get; set; }

    public string Lastname { get; set; }
}

Tags:

programming

Comments

1/27/2010 12:24:48 PM #

KillBill

I loved that explanation. Well structured & applicable.

KillBill

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen