user2143207
user2143207

Reputation: 69

How to return a LINQ Anonymoustype to a typed collection

I am having below LINQ which I want to return into a collectionList.

var StudIds = from _NewIds in NewIds.AsEnumerable()
           join _OldIds in allOldIds.AsEnumerable()
           on _NewIds.Field<int>("Id") equals _OldIds.Field<int>("Id")
           where _NewIds.Field<Boolean>("IsExist") == true && _NewIds.Field<string>("FieldName") == "FinalValue"
           select new
           {
               Id = _NewIds.Field<int>("Id"),
               Name = _NewIds.Field<string>("Name"),
               Value = _NewIds.Field<decimal>("PRice")
           };



List<std> lstCustomWebsiteVerifiedIndex = new List<std>();

This Std class is haivg Id, name and Value as datamember.

Any idea how to typecast this?

Upvotes: 0

Views: 47

Answers (2)

DavidG
DavidG

Reputation: 118937

There's no need to use an anonymous type, just project directly to your std type:

var StudIds = from _NewIds in NewIds.AsEnumerable()
              join _OldIds in allOldIds.AsEnumerable()
              on _NewIds.Field<int>("Id") equals _OldIds.Field<int>("Id")
              where _NewIds.Field<Boolean>("IsExist") == true && _NewIds.Field<string>("FieldName") == "FinalValue"
              select new std
              {
                  Id = _NewIds.Field<int>("Id"),
                  Name = _NewIds.Field<string>("Name"),
                  Value = _NewIds.Field<decimal>("PRice")
              };

Upvotes: 1

Habib
Habib

Reputation: 223187

Instead of projecting it to an anonymous class in the first place you should use std class like:

  select new std
      {
          Id = _NewIds.Field<int>("Id"),
          Name = _NewIds.Field<string>("Name"),
          Value = _NewIds.Field<decimal>("PRice")
      };

and later you can do:

List<std> lstCustomWebsiteVerifiedIndex  = StudIds.ToList();

But if your class std is generated through some framework (like Entity framework) then you will not be able to use projection, in that case you will need a temporary class.

Also if you can't modify existing code (with anonymous class) then you can use your query to project to your list like:

List<std> lstCustomWebsiteVerifiedIndex = StudIds.Select(r=> new std
                                            {
                                              Id = r.Id, 
                                              Name = r.Name, 
                                              Value = r.Value,
                                            })
                                           .ToList();

Upvotes: 1

Related Questions