tobeghost
tobeghost

Reputation: 35

Using Anonymous Type from LINQ to SQL

I'm making a project and I get an error for Anonymous Type in the project. Problem is how to get and use anonymous type from other class like function.

public IList GetReferenceList()
{
    var result = from r in entity.Reference
                 join d in entity.Reference_Detail on r.id equals d.refid
                 select new { ID = d.id, REFNAME = r.Name, DETAIL=d.Name };
    return result.ToList();
}

Problem is here. What should i write return type for this function, and I want to use in foreach.

private void Form1_Load(object sender, EventArgs e)
{
     var data = GetReferenceList();
     foreach(var item in data)
     {
         //I didn't use field in here.
     }
}

I dont want to make a class like that, and use the class.

public class MyList()
{
   public int ID { get; set; }
   public string REFNAME { get; set; }
   public string DETAIL { get; set; }
}

public List<MyList> GetReferenceList()
{
    var result = from r in entity.Reference
                 join d in entity.Reference_Detail on r.id equals d.refid
                 select new MyList { ID = d.id, REFNAME = r.Name, DETAIL=d.Name };
    return result.ToList();
}

private void Form1_Load(object sender, EventArgs e)
{
     List<MyList> data = GetReferenceList();
     foreach(MyList item in data)
     {
         //I can use field in here.
     }
}

I have 100 query like that. and if I make like that, will be 100 class for query.

Please, help me.

Upvotes: 0

Views: 579

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109271

I'm not saying you should do this, on the contrary, but you can use dynamics to return anonymous types and address their properties later:

public IEnumerable<dynamic> GetReferenceList()
{
    return from r in entity.Reference
           join d in entity.Reference_Detail on r.id equals d.refid
           select new { ID = d.id, REFNAME = r.Name, DETAIL = d.Name };
}

And in consuming code:

 var data = GetReferenceList();
 foreach (var item in data)
 {
     var name = (string)(item.REFNAME);
     ...
 }

You'll soon start to hate this approach. You'll keep casting the dynamic types to runtime types, you won't have intellisense (on item. in this case), you won't have compile-time checking, so it's error-prone and susceptible to all kinds of subtle bugs. Do yourself a favor and use named types.

Upvotes: 1

Related Questions