Is it possible to include or exclude column within linq Select?
var numberOfYears = Common.Tool.NumberOfYear;
var list = users.Select(item => new
{
Id = item.Id,
Name= item.Name,
City= Item.Address.City.Name,
STATUS = Item.Status,
if(numberOfYears == 1)
{
Y1 = item.Records.Y1,
}
if(numberOfYears == 2)
{
Y1 = item.Records.Y1,
Y2 = item.Records.Y2,
}
if(numberOfYears == 3)
{
Y1 = item.Records.Y1,
Y2 = item.Records.Y2,
Y3 = item.Records.Y3,
}
}).ToList();
}
The idea is that i want to display Y1,Y2,Y3 only if has values
Thanks to the beauty of the dynamic keyword what you need is now possible in C#. Below an example:
public class MyItem
{
public string Name { get; set; }
public int Id { get; set; }
}
static void Main(string[] args)
{
List<MyItem> items = new List<MyItem>
{
new MyItem
{
Name ="A",
Id = 1,
},
new MyItem
{
Name = "B",
Id = 2,
}
};
var dynamicItems = items.Select(x => {
dynamic myValue;
if (x.Id % 2 == 0)
myValue = new { Name = x.Name };
else
myValue = new { Name = x.Name, Id = x.Id };
return myValue;
}).ToList();
}
This will return a list of dynamic objects. One with 1 property and one with 2 properties.
Try this approach:
var numberOfYears = Common.Tool.NumberOfYear;
var list = users.Select(item => new
{
Id = item.Id,
Name = item.Name,
City = Item.Address.City.Name,
STATUS = Item.Status,
Y1 = numberOfYears > 0 ? item.Records.Y1 : 0,
Y2 = numberOfYears > 1 ? item.Records.Y2 : 0,
Y3 = numberOfYears > 2 ? item.Records.Y3 : 0
}).ToList();
Instead of 0, add your default value or null.
Update:
According to your comments, the only option for you is to go dynamic. Here's example with dynamics:
var numberOfYears = 3;
var list = users.Select(x =>
{
dynamic item = new ExpandoObject();
item.Id = x.Id;
item.Name = x.Name;
item.Status = x.Status;
var p = item as IDictionary<string, object>;
var recordsType = x.Records.GetType();
for (var i = 1; i <= numberOfYears; ++i)
p["Y" + i] = recordsType.GetProperty("Y" + i).GetValue(x.Records);
return item;
}).ToList();
You can use the ExpandoObject like this:
var data = providers.Select(provider =>
{
dynamic excelRow = new ExpandoObject();
excelRow.FirstName = provider.FirstName ?? "";
excelRow.MiddleName = provider.MiddleName ?? "";
excelRow.LastName = provider.LastName ?? "";
// Conditionally add columns to the object...
if (someCondition)
{
excelRow.Property1ForCondition = provider.Property1ForCondition;
excelRow.Property2ForCondition = provider.Property2ForCondition;
}
excelRow.DueDate = provider.DueDate ?? null;
.
.
.
return excelRow;
});
Another variation of the above code can be:
var data = new List<ExpandoObject>();
providers.ForEach(provider =>
{
dynamic excelRow = new ExpandoObject();
excelRow.FirstName = provider.FirstName ?? "";
excelRow.MiddleName = provider.MiddleName ?? "";
excelRow.LastName = provider.LastName ?? "";
// Conditionally add columns to the object...
if (someCondition)
{
excelRow.Property1ForCondition = provider.Property1ForCondition;
excelRow.Property2ForCondition = provider.Property2ForCondition;
}
excelRow.DueDate = provider.DueDate ?? null;
.
.
.
data.Add(excelRow);
});
Related
Below is my linq code and it works. My question is how I can "reuse" those part new ContactResponse, and new AddressResponse in a function to reuse it in another query?
var queryset = (
from a in _repoWrapper.Workshop.FindAll()
where (a.IsActive == true && a.Entity.EntityType.Code == Global.EntityTypeServiceCenterCode)
select new ServiceCenterResponse
{
Id = a.Id,
Name = a.Name,
EntityId = a.EntityId,
Contacts = a.WorkshopContacts.Select(p => new ContactResponse
{
Id = p.Contact.Id,
Type = p.Contact.ContactType.Description,
Code = p.Contact.ContactType.Code,
Value = p.Contact.Value
}).ToList(),
Addresses = a.WorkshopAddresses.Select(p => new AddressResponse
{
Id = p.Address.Id,
AddressType = p.Address.AddressType.Code,
StreetLine1 = p.Address.StreetLine1,
StreetLine2 = p.Address.StreetLine2,
City = p.Address.City,
State = p.Address.State,
PostCode = p.Address.PostCode,
Country = p.Address.Country,
Longitude = p.Address.Longitude,
Latitude = p.Address.Latitude,
Others = p.Address.Others
}).ToList()
}
);
If I correct understand your question, then try this:
Func<WorkshopContact, ContactResponse> contactResponseProjection= p => new ContactResponse
{
Id = p.Contact.Id,
Type = p.Contact.ContactType.Description,
Code = p.Contact.ContactType.Code,
Value = p.Contact.Value
};
And use:
...
Contacts = a.WorkshopContacts.Select(contactResponseProjection).ToList(),
...
Linq has a parameter of type Func in the Select method. This means that you can pass a method to it.
Let me try to do an example.
List<int> list = new List<int> { 1, 2, 3 };
list.Select(AddOne);
where AddOne is a method that you can declare and must have a parameter of type int and a return of whatever you'd like to return. eg.
public int AddOne(int value)
{
return value + 1;
}
Below is the query,
List<int> groupIdList = {1, 2};
var clientGroupData = from cge in base.context.Set<ClientGroupEngagement>()
join cg in base.context.Set<ClientGroup>() on cge.ClientGroupID equals cg.ClientGroupID
join cgu in base.context.Set<ClientGroupUser>() on cg.ClientGroupID equals cgu.ClientGroupID
join eng in base.context.Set<Engagement>() on cge.EngagementID equals eng.EngagementID
join cdc in base.context.Set<CountryDataCenter>()
on new { eng.CountryID, eng.EngagementVersion } equals new { cdc.CountryID, cdc.EngagementVersion }
join dc in base.context.Set<DataCenter>()
on cdc.DataCenterID equals dc.DataCenterID
join dcuri in base.context.Set<DataCenterURI>()
on new { dc.DataCenterID, cdc.EngagementVersion } equals new { dcuri.DataCenterID, dcuri.EngagementVersion }
join uritype in base.context.Set<URIType>()
on dcuri.URITypeID equals uritype.URITypeID
where groupIdList.Contains(cgu.ClientGroupID)
&& cg.IsActive
&& cdc.IsActive
&& dc.IsActive
&& dcuri.IsActive
&& uritype.IsActive
&& (dcuri.URITypeID == (int)URITypeEnum.WebUri || dcuri.URITypeID == (int)URITypeEnum.AppUri)
select new ClientGroupUserEngagementModel
{
EngagementId = cge.EngagementID,
EngagementDescription = eng.EngagementDescription,
EngagementStatusId = eng.EngagementStatusID,
ClientGroupId = cg.ClientGroupID,
ClientGroupGuid = cg.ClientGroupGUID,
ClientGroupName = cg.ClientGroupName,
UserId = cgu.ClientUserID,
FirstName = cgu.FirstName,
LastName = cgu.LastName,
IsGroupUserActive = cgu.IsActive,
LocatorDataModel = new LocatorDataModel
{
DatacenterId = cdc.DataCenterID,
DatacenterName = dc.DataCenterName,
EngagementVersion = cdc.EngagementVersion,
Uri = dcuri.URI,
UriTypeId = dcuri.URITypeID
},
};
var result = await clientGroupData.ToListAsync();
I am expecting list of LocatorDataModel in the result set. EngagementId is key which will be unique.
Currently it is pulling *2 records due to condition
(dcuri.URITypeID == (int)URITypeEnum.WebUri || dcuri.URITypeID == (int)URITypeEnum.AppUri)
How can get result like
Engagementid 1 : dataurl1 dataurl2
Engagementid 2: dataurl3 dataurl4, dataurl5
etc.
Any help is appreciated.
I think below sample code can help you:
var list = new[]
{
new { Engagementid = 1, Dataurl = "dataurl1"},
new { Engagementid = 1, Dataurl = "dataurl2"},
new { Engagementid = 2, Dataurl = "dataurl3"},
new { Engagementid = 2, Dataurl = "dataurl4"},
new { Engagementid = 2, Dataurl = "dataurl5"}
};
var result =
list.GroupBy(g => g.Engagementid)
.Select(c => new {Engagementid = c.Key, Dataurls = string.Join(",", c.Select(x=> x.Dataurl).ToList())})
.ToList();
That result will be:
[0]: { Engagementid = 1, Dataurls = "dataurl1,dataurl2" }
[1]: { Engagementid = 2, Dataurls = "dataurl3,dataurl4,dataurl5" }
I am looking for the best algorithm to compare 2 collections and determine which element got added and which element got removed.
private string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement, ICollection<UserInvolvement> oldInvolvement)
{
//I defined the new and old dictionary's for you to know what useful data is inside UserInvolvement.
//Both are Dictionary<int, int>, because The Involvement is just a enum flag. Integer. UserId is also Integer.
var newDict = newInvolvement.ToDictionary(x => x.UserID, x => x.Involvement);
var oldDict = oldInvolvement.ToDictionary(x => x.UserID, x => x.Involvement);
//I Want to compare new to old -> and get 2 dictionaries: added and removed.
var usersAdded = new Dictionary<int, Involvement>();
var usersRemoved = new Dictionary<int, Involvement>();
//What is the best algoritm to accomplish this?
return GetInvolvementLogging(usersAdded, usersRemoved);
}
private string GetInvolvementLogging(Dictionary<int, Involvement> usersAdded, Dictionary<int, Involvement> usersRemoved)
{
//TODO: generate a string based on those dictionaries.
return "Change in userinvolvement: ";
}
Added elements are only in newDict removed only in oldDict
var intersection = newDict.Keys.Intersect(oldDict.Keys);
var added = newDict.Keys.Except(intersection);
var removed = oldDict.Keys.Except(intersection);
EDIT
I modify your base function, dictionaries is no neded.
Example UserInvolvement implementation
class UserInvolvement
{
public int UserId;
public string Name;
public string OtherInfo;
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
UserInvolvement p = obj as UserInvolvement;
if ((System.Object)p == null)
{
return false;
}
return (UserId == p.UserId) && (Name == p.Name) && (OtherInfo == p.OtherInfo);
}
public override string ToString()
{
return $"{UserId} - {Name} - {OtherInfo}";
}
}
And example function:
private static string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement,
ICollection<UserInvolvement> oldInvolvement)
{
var intersection = newInvolvement.Select(x => x.UserId).Intersect(oldInvolvement.Select(x => x.UserId));
var addedIds = newInvolvement.Select(x => x.UserId).Except(intersection);
var removedIds = oldInvolvement.Select(x => x.UserId).Except(intersection);
List<UserInvolvement> modifiedUI = new List<UserInvolvement>();
foreach (var i in intersection)
{
var ni = newInvolvement.First(a => a.UserId == i);
var oi = oldInvolvement.First(a => a.UserId == i);
if (!ni.Equals(oi))
{
modifiedUI.Add(ni);
}
}
List<UserInvolvement> addedUI = newInvolvement.Where(x => addedIds.Contains(x.UserId)).Select(w => w).ToList();
List<UserInvolvement> removedUI = oldInvolvement.Where(x => removedIds.Contains(x.UserId)).Select(w => w).ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Added");
foreach (var added in addedUI)
{
sb.AppendLine(added.ToString());
}
sb.AppendLine("Removed");
foreach (var removed in removedUI)
{
sb.AppendLine(removed.ToString());
}
sb.AppendLine("Modified");
foreach (var modified in modifiedUI)
{
sb.AppendLine(modified.ToString());
}
return sb.ToString();
}
And my test function:
static void Main(string[] args)
{
List<UserInvolvement> newUI = new List<UserInvolvement>()
{
new UserInvolvement()
{
UserId = 1,
Name = "AAA",
OtherInfo = "QQQ"
},
new UserInvolvement()
{
UserId = 2,
Name = "BBB",
OtherInfo = "123"
},
new UserInvolvement()
{
UserId = 4,
Name = "DDD",
OtherInfo = "123ert"
}
};
List<UserInvolvement> oldUI = new List<UserInvolvement>()
{
new UserInvolvement()
{
UserId = 2,
Name = "BBBC",
OtherInfo = "123"
},
new UserInvolvement()
{
UserId = 3,
Name = "CCC",
OtherInfo = "QQ44"
},
new UserInvolvement()
{
UserId = 4,
Name = "DDD",
OtherInfo = "123ert"
}
};
string resp = GetInvolvementLogging(newUI, oldUI);
WriteLine(resp);
ReadKey();
WriteLine("CU");
}
Result is:
Added
1 - AAA - QQQ
Removed
3 - CCC - QQ44
Modified
2 - BBB - 123
You could try with Linq:
var usersAdded = newDict.Except(oldDict);
var usersRemoved = oldDict.Except(newDict);
If you need dictionaries as a result you can cast:
var usersAdded = newDict.Except(oldDict).ToDictionary(x => x.Key, x => x.Value);
var usersRemoved = oldDict.Except(newDict).ToDictionary(x => x.Key, x => x.Value);
Think best algorithm will be
foreach (var newItem in newDict)
if (!oldDict.ContainsKey(newItem.Key) || oldDict[newItem.Key]!=newItem.Value)
usersAdded.Add(newItem.Key, newItem.Value);
foreach (var oldItem in oldDict)
if (!newDict.ContainsKey(oldItem.Key) || newDict[oldItem.Key]!=oldItem.Value)
usersRemoved.Add(oldItem.Key, oldItem.Value);
Finally this is my implementation of GetInvolvementLogging:
(the implementation of the string builder method is irrelevant for my question here)
private string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement, ICollection<UserInvolvement> oldInvolvement)
{
//I defined the new and old dictionary's to focus on the relevant data inside UserInvolvement.
var newDict = newInvolvement.ToDictionary(x => x.UserID, x => (Involvement)x.Involvement);
var oldDict = oldInvolvement.ToDictionary(x => x.UserID, x => (Involvement)x.Involvement);
var intersection = newDict.Keys.Intersect(oldDict.Keys); //These are the id's of the users that were and remain involved.
var usersAdded = newDict.Keys.Except(intersection);
var usersRemoved = oldDict.Keys.Except(intersection);
var addedInvolvement = newDict.Where(x => usersAdded.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
var removedInvolvement = oldDict.Where(x => usersRemoved.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
//Check if the already involved users have a changed involvement.
foreach(var userId in intersection)
{
var newInvolvementFlags = newDict[userId];
var oldInvolvementFlags = oldDict[userId];
if ((int)newInvolvementFlags != (int)oldInvolvementFlags)
{
var xor = newInvolvementFlags ^ oldInvolvementFlags;
var added = newInvolvementFlags & xor;
var removed = oldInvolvementFlags & xor;
if (added != 0)
{
addedInvolvement.Add(userId, added);
}
if (removed != 0)
{
removedInvolvement.Add(userId, removed);
}
}
}
return GetInvolvementLogging(addedInvolvement, removedInvolvement);
}
So we've got two methods shown below:
Method 1
private IEnumerable<object> CreateCentreViewModelForExport(IQueryable<CentreTranslation> centreTranslation)
{
return centreTranslation.Select(s => new
{
id = s.Centre.id,
centreTranslationId = s.id,
name = s.Centre.name,
number = s.Centre.number,
date_opened = s.Centre.date_opened,
address_line_1 = s.address_line_1,
address_line_2 = s.address_line_2,
address_line_3 = s.address_line_3,
city = s.city,
county = s.county,
country = s.Centre.Country.name,
//country_id = s.Centre.country_id,
translatedCountry = s.country,
postcode = s.postcode,
hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
about = s.about,
virtualTour = s.Centre.virtual_tour,
directions = s.directions,
phone = s.Centre.phone,
fax = s.Centre.fax,
email = s.Centre.email,
lat = s.Centre.position.Latitude,
lng = s.Centre.position.Longitude,
imageCount = s.Centre.image_count,
translatedCentreName = s.name,
amenities = s.amenities ,
features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
{
id = s2.id,
name = s2.Feature.name,
selected = s2.selected
}),
businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about,
language_group = s.Language.language_group,
culture = s.Language.cuture
});
}
Method 2
private IQueryable<CentreViewModel> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
return centreTranslation.Select(s => new CentreViewModel()
{
id = s.Centre.id,
centreTranslationId = s.id,
name = s.Centre.name,
number = s.Centre.number,
date_opened = s.Centre.date_opened,
address_line_1 = s.address_line_1,
address_line_2 = s.address_line_2,
address_line_3 = s.address_line_3,
city = s.city,
county = s.county,
//country = s.Centre.Country.name,
country_id = s.Centre.country_id,
translatedCountry = s.country,
postcode = s.postcode,
hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
about = s.about,
virtualTour = s.Centre.virtual_tour,
directions = s.directions,
phone = s.Centre.phone,
fax = s.Centre.fax,
email = s.Centre.email,
lat = s.Centre.position.Latitude,
lng = s.Centre.position.Longitude,
imageCount = s.Centre.image_count,
translatedCentreName = s.name,
amenities = s.amenities,
features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
{
id = s2.id,
name = s2.Feature.name,
selected = s2.selected
}),
businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about
});
}
As can be seen there is a lot of duplicate code. The second method returns a strongly typed view model, while the first returns an object due to the inclusion of two extra properties (language_group and culture).
The second method is used to populate an MVC view, the second for an export to Excel function.
What's the best way of re factoring this to minimize the duplication?
I would create a DTO class and have a setter method on it that takes in a IQueryable centreTranslation. You then pass the object to the class and set all those values in that class and pass the dto back to the original method you have there.
public class SomeDto
{
//All of the properties your setting in the other method
public void SetDto(IQueryable<CentreTranslation> centreTranslation)
{
//call methods that set all the properties
}
private SetAddress(IQueryable<CentreTranslation> centreTranslation)
{
//set only address properties
}
I would also make smaller setter methods for the types like everything that has to do with an address make a private method on the dto object called SetAddress and go down the line.
After you have your DTO object you can use a tool like Automapper to map directly from your DTO object to a ViewModel object. This would give you maximum flexability for more refactoring throughout the app.
private ViewModel createViewModel(Dto)
{
return Mapper.Map(Dto, ViewModel);
}
Create a static FromCentreTranslation method in the CentreViewModel class, and put all initialization there:
public class CentreViewModel
{
....
public static CentreViewModel FromCentreTranslation(CentreTranslation source)
{
CentreViewModel result = new CentreViewModel();
result.id = source.Centre.id,
result.centreTranslationId = source.id,
result.name = source.Centre.name,
....
result.businessLoungeAbout = source.ProductTranslations
.Where(w => w.Product.id == (int)Products.BusinessLounge)
.FirstOrDefault().about,
result.dayOfficeAbout = source.ProductTranslations
.Where(w => w.Product.id == (int)Products.DayOffice)
.FirstOrDefault().about
return result;
}
}
You can then refactor the original two methods like:
private IEnumerable<object> CreateCentreViewModelForExport
(IQueryable<CentreTranslation> centreTranslation)
{
return centreTranslation.Select(s => new
{
centreViewModel = CentreViewModel.FromCentreTranslation(s),
language_group = s.Language.language_group,
culture = s.Language.cuture
}
}
and
private IQueryable<CentreViewModel> CreateCentreViewModel
(IQueryable<CentreTranslation> centreTranslation)
{
return centreTranslation.Select(s => CentreViewModel.FromCentreTranslation(s)),
}
private IQueryable<object> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
return centreTranslation.Select(s => new
{
model = new CentreViewModel()
{
id = s.Centre.id,
centreTranslationId = s.id,
name = s.Centre.name,
[...]
}
language_group = s.Language.language_group,
culture = s.Language.cuture
}
}
Take a look at my code here:
public static ItemType GetItem(int id)
{
ItemType it = new ItemType();
using (var context = matrix2.matrix2core.DataAccess.Connection.GetContext())
{
var q = (from ci in context.Item
where ci.ID == id
let TemplateID = ci.TemplateID
let Groups = from x in context.CriteriaGroup
where x.TemplateID == TemplateID
select new
{
x
}
let CriteriaItems = from x in context.CriteriaItem
where Groups.Select(y => y.x.ID).Contains(x.CriteriaGroupID)
select new
{
x
}
select new
{
ci.ID,
ci.Name,
ci.CategoryID,
ci.Description,
ci.ItemValue,
TemplateID,
Groups,
CriteriaItems,
ItemValues = from x in context.ItemValue
where x.ItemID == id
select new
{
x,
CriteriaID = x.CriteriaItem.Criteria.ID
}
}).FirstOrDefault();
if (q != null)
{
it.ID = q.ID;
it.CategoryID = q.CategoryID;
it.Name = q.Name;
it.TemplateID = q.TemplateID;
it.Description = q.Description;
it.CriteriaGroups = new List<CriteriaGroupType>();
it.CriteriaItems = new List<CriteriaItemType>();
it.ItemValues = new List<ItemValueType>();
foreach (var x in q.ItemValues)
{
ItemValueType ivt = new ItemValueType();
ivt.CriteriaItemID = x.x.CriteriaItemID;
ivt.CriteriaID = x.CriteriaID;
ivt.Data = x.x.Data;
ivt.ID = x.x.ID;
ivt.ItemID = x.x.ItemID;
it.ItemValues.Add(ivt);
}
/////////error when I added the orderby clause
foreach (var x in q.Groups.OrderBy(x => x.x.SortOrder))
{
CriteriaGroupType cgt = new CriteriaGroupType();
cgt.ID = x.x.ID;
cgt.Name = !string.IsNullOrEmpty(x.x.Name) ? x.x.Name : "Group" + x.x.ID;
cgt.SortOrder = x.x.SortOrder;
cgt.TemplateID = x.x.TemplateID;
it.CriteriaGroups.Add(cgt);
}
/////////error when I added the orderby clause
foreach (var temp in q.CriteriaItems.OrderBy(x => x.x.SortOrder))
{
CriteriaItemType cit = new CriteriaItemType();
cit.ID = temp.x.ID;
cit.CriteriaGroupID = temp.x.CriteriaGroupID;
cit.GroupName = (temp.x.Name != null) ? temp.x.Name : "Group" + temp.x.ID;
cit.CriteriaID = temp.x.CriteriaID;
cit.CriteriaName = temp.x.Criteria.Name;
cit.Name = !string.IsNullOrEmpty(temp.x.Name) ? temp.x.Name : temp.x.Criteria.Name;
cit.Options = temp.x.Options;
it.CriteriaItems.Add(cit);
}
}
}
return it;
}
Instead of letting SQL handle the sorting (OrderBy) I wanted asp.net to do the sorting instead. I took the sorting out of the SQL linq query and put it on the foreach loop. When I did that I got the error. Is there a way to fix this?
You should be able to go from IQueryable to IEnumerable with a simple
var q2 = q.ToList();
What I meant of course was :
var groups = q.Groups.ToList();