Anonymous Type List

Here is my code

var personalInfoQuery = from t in crnnsupContext.Tombstones.Include("ProvState") join n in crnnsupContext.NursingSchools on t.NursingSchool equals n.SchoolID where t.RegNumber == _username select new { t, n }; 

then I'm trying to put personalInfoQuery in a list like

 List<> personalInfoResult = personalInfoQuery.ToList(); 

but how to present an anonymous type in a list?

I need to insert it into the cache so Cache.Insert("personalInfo", personalInfoQuery.ToList()) then Cache["personalInfo"] becomes an object, how can i read data from it?

+4
source share
2 answers

Since your type must be used by more than one method (it must be created by one method and read by another), it should not use an anonymous type. Just create a simple type:

 public class TombstoneNursingSchool { public Tombstone Tombstone { get; set; } public NursingSchool NursingSchool { get; set; } } 

create it like this:

 var personalInfoQuery = from t in crnnsupContext.Tombstones.Include("ProvState") join n in crnnsupContext.NursingSchools on t.NursingSchool equals n.SchoolID where t.RegNumber == _username select new TombstoneNursingSchool { Tombstone = t, NursingSchool = n }; 

create a list like this:

 List<TombstoneNursingSchool> personalInfoResult = personalInfoQuery.ToList(); 

put it in the cache as follows:

 Cache.Insert("personalInfo", personalInfoQuery.ToList()) 

pull it out of the cache and read it as follows:

 foreach(var tn in (List<TombstoneNursingSchool>)Cache["personalInfo"]) { // do something with tn.Tombstone and tn.NursingSchool } 

Anonymous types are convenient in one method, but they are not suitable for every situation. Don't be afraid to make a named type if you need one.

+3
source

This is exactly the var keyword.

So, instead of:

 List<> personalInfoResult = personalInfoQuery.ToList(); 

use this:

 var personalInfoResult = personalInfoQuery.ToList(); 

The compiler will accurately determine the type that you do not need to specify. This is by no means unsafe, it is still 100% typed, even if you have not identified the type.

+3
source

Source: https://habr.com/ru/post/1401219/


All Articles