NIlesh Lanke
NIlesh Lanke

Reputation: 1243

How to extract result of Linq Expression?

My result Expression is

 var result = dtFields.AsEnumerable().Join(dtCDGroup.AsEnumerable(),
                                fieldList=>fieldList.Field<string>("CDGroupID"),
                                cd=>cd.Field<string>("CDGroupID"),
                                (fieldList,cd) => new 
                                {
                                    FieldID = fieldList.Field<string>("FieldID"),
                                    Name = cd.Field<string>("Name"),
                                    CDCaption = fieldList.Field<string>("CDCaption"),
                                    Priority = ((cd.Field<string>("Priority") == null) ? 99 : cd.Field<int>("Priority")),
                                    fldIndex = fieldList.Field<string>("fldIndex")
                                }).OrderBy(result => result.Priority).ThenBy(result => result.fldIndex);

Casting above result to array or list throws an invalid cast exception. How can extract result of above expression?

Upvotes: 0

Views: 154

Answers (2)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79929

Try to add a strongly typed type:

public class NewModule
{
    public int FieldID { get; set; }
    public string Name { get; set; }
    public string CDCaption { get; set; }
    public int Priority { get; set; }
    public int fldIndex { get; set; }
}

instead of the anonymous type then you could use ToList<NewModule>() like this:

var result = dtFields.AsEnumerable().Join(dtCDGroup.AsEnumerable(),
                            fieldList=>fieldList.Field<string>("CDGroupID"),
                            cd=>cd.Field<string>("CDGroupID"),
                            (fieldList,cd) => new NewModule
                            {
                                FieldID = fieldList.Field<string>("FieldID"),
                                Name = cd.Field<string>("Name"),
                                CDCaption = fieldList.Field<string>("CDCaption"),
                                Priority = ((cd.Field<string>("Priority") == null) ? 99 : cd.Field<int>("Priority")),
                                fldIndex = fieldList.Field<string>("fldIndex")
                            }).OrderBy(result => result.Priority)
                            .ThenBy(result => result.fldIndex)
                            .ToList<NewModule>();

Upvotes: 0

Alex
Alex

Reputation: 2468

Add .ToArray() or .ToList() call respectively

Upvotes: 2

Related Questions