How to sort Linq query grouped results - linq

I have a query that returns me a list of Categories grouped by Univers and ordered by Univers name. I would like the list of results also being ordered by category name (C.Name), here is my Linq query:
public static IEnumerable<IGrouping<String, String>> GetCatalogUnivCateg(){
var contexte = new AV2_Entities();
var query = from C in contexte.Category
group C.Name by C.Univers.Name into g
orderby g.Key
select g;
return query.ToList();
}
I would like to understand how is applied the group by, when the results has an orderby.

Add ordering when selecting group:
var query = from c in contexte.Category
group c by c.Univers.Name into g
orderby g.Key
select g.OrderBy(x => x.Name) // sort by name
.Select(x => x.Name); // project if you need just names
Unfortunately you can't return sorted results if you are returning IGrouping from method. Also IGrouping implementations are internal, so you can't just return some new grouping object. I suggest you to create DTO class, like:
public class UniversCategories
{
public string UniversName { get; set; }
public IEnumerable<string> Categories { get; set; }
}
And return instances of this class from your method
var query = from c in contexte.Category
group c by c.Univers.Name into g
orderby g.Key
select new UniversCategories {
UniversName = g.Key,
Categories = g.Select(x => x.Name).OrderBy(n => n)
};

Related

Left Join using LAMBDA to get Result in API

How to implement this Join which is in the code below into C# using LAMBDA
Select
VD.Id
, VD.BusinessAddress
, VD.BusinessDesc
, VD.BusinessEmail
, VD.BusinessName
, VD.BusinessZip
, VD.ContactPerson
, VD.ContactNo
, VD.ProfileUrl
, L.Name
, BC.BusinessCategory
from vendorDomain VD WITH(NOLOCK)
left Join Location L WITH(NOLOCK) ON VD.City = L.Id
left join Business_Category BC WITH(NOLOCK) ON VD.BusinessCategory = BC.BusinessId
where VD.IsDeleted = 0
I have to implement the join operation in the following API:
[HttpGet]
public async Task<IActionResult> Get()
{
var VendorList =await _vendorRepository.Query().Where(x => x.IsDeleted == false).ToListAsync();
return Ok(VendorList);
}
There are alot of examples out there but are way to confusing for a novice developer..
EDIT:
This is what I have tried as of now:
var employees = from vndr in context.vendorDomain
join C in context.Location on vndr.City equals C.Id into dep
from dept in dep.DefaultIfEmpty()
select new
{
vndr.BusinessAddress,
vndr.BusinessDesc,
vndr.BusinessEmail,
vndr.BusinessName,
vndr.BusinessWebsite,
vndr.BusinessZip,
vndr.ContactNo,
vndr.ContactPerson,
vndr.Created_At,
vndr.ProfileUrl,
vndr.Url,
dept.Name
};
We will do things first: do the joins and create a view model class that you will return. Because returning anonymous object and using dynamic does get messy.
ViewModel for the joined entities:
public class EmployeesViewModel
{
public string BusinessAddress { get; set; }
public string BusinessDesc { get; set; }
public string BusinessEmail { get; set; }
/* ....all remaining properties */
}
Then we join them properly and select them as an EmployeeViewModel:
var employees = from vndr in context.vendorDomain
join loc in context.Location on vndr.City equals loc.Id
join bus in context.Business_Category on vndr.BusinessCategory = bus.BusinessId
select new EmployeeViewModel
{
BusinessAddress = vndr.BusinessAddress,
BusinessDesc = vndr.BusinessDesc,
BusinessEmail = vndr.BusinessEmail,
/* ... remaining properties here*/
};
Or, if you want the method syntax:
var employees = context.vendorDomain
.Join(context.Location,
vndr => vndr.City,
loc => loc.Id,
(vndr, loc) => new { vndr, loc,})
.Join(context.Business_Category,
vndr_loc.vndr.BusinessCategory,
bus.BusinessId,
(vndr_loc, bus) => new {vndr_loc.vndr, vndr_loc.loc, bus})
.Select(x => new EmployeeViewModel{
BusinessAddress = vndr.BusinessAddress,
BusinessDesc = vndr.BusinessDesc,
BusinessEmail = vndr.BusinessEmail,
/* ... remaining properties here*/
});
As per your comment, you need to print the vendorList after the join. Now that is pretty vague, but I assume you want to submit both to your client / view, so again, we create a ViewModel class for it:
public class EmployeeVendorListViewModel
{
public VendorList VendorList { get; set; }
public EmployeeViewModel Employees { get; set; }
}
The last thing we do is glue it all together in your ActionMethod and return it:
[HttpGet]
public async Task<IActionResult> Get()
{
//renamed using a lower case "v"
var vendorList = await _vendorRepository.Query()
.Where(x => x.IsDeleted == false)
.ToListAsync();
//the join from earlier. You should put it in a repo somewhere, so it does not clutter your controller
var employees = from vndr in context.vendorDomain
join loc in context.Location on vndr.City equals loc.Id
join bus in context.Business_Category on vndr.BusinessCategory = bus.BusinessId
select new EmployeeViewModel
{
BusinessAddress = vndr.BusinessAddress,
BusinessDesc = vndr.BusinessDesc,
BusinessEmail = vndr.BusinessEmail,
/* ... remaining properties here*/
};
//create the final view model and return it
var vm = new EmployeeVendorListViewModel
{
VendorList = vendorList,
Employees = employees
}
return Ok(vm);
}
If you want to use NOLOCK in your query, you have to wrap it in a TransactionScope. This has already been answered here on StackOverflow: NOLOCK with Linq to SQL

Linq results type?

I would like to replace "var" with the actual type definition. I believe it returns an IEnumerable<>, but I can't figure out what to put for T? I tried debugging with GetType(), but still don't get it...
var LinqResults = from row in dt.AsEnumerable()
orderby row.Field<string>("Category"), row.Field<int>("WorkOrderVersion")
group row by new { Category = row.Field<string>("Category"), WorkOrderVersion = row.Field<int>("WorkOrderVersion") } into grp
select new
{
Category = grp.Key.Category,
WorkOrderVersion = grp.Key.WorkOrderVersion,
};
You can't combine a use of an anonymous type with a specific type because anonymous types provide no name for you to put in for a T inside IEnumerable<T>. In fact, use of anonymous types is an important use case for adding var to the C# language in the first place.
You can define a named type for the result, lie this:
class VersionedWorkOrder {
public string Category { get; set; }
public int WorkOrderVersion { get; set; }
}
IEnumerable<VersionedWorkOrder> linqResults = from row in dt.AsEnumerable()
orderby row.Field<string>("Category"), row.Field<int>("WorkOrderVersion")
group row by new { Category = row.Field<string>("Category"), WorkOrderVersion = row.Field<int>("WorkOrderVersion") } into grp
select new VersionedWorkOrder {
Category = grp.Key.Category,
WorkOrderVersion = grp.Key.WorkOrderVersion
};

Full outer join linq using union

I have two lists
var left={[ID=1,Name='A',Qty1=0,Qty2=5],[ID=2,Name=B,Qty1=0,Qty2=52]};
var right={[ID=1,Name='A',Qty1=57,Qty2=0],[ID=2,Name=B,Qty1=84,Qty2=0]};
var outer=left.union(right);
I want to get the following result:
outer={[ID=1,Name='A',Qty1=57,Qty2=5],[ID=2,Name=B,Qty1=84,Qty2=52]}
How do I get that? How to write the comparator class?
Edit:
I have two lists
var target=(...new ClassA{ID=a.ID,Name=a.Name,TargetQty=b.TargetValue}).ToList();
var sales=(....new ClassA{ID=a.ID,Name=a.Name,SalesQty=b.SaleValue}).ToList();
Now I want a full outer join. How can I get that?
It sounds like you possibly want an inner join:
var query = left.Join(right, l => l.Id, r => r.Id,
(l, r) => new { l.Id, l.Name, r.Qty1, l.Qty2 });
(You may want to join on both Id and Name; it's not clear whether the Id is enough.)
In this case union will not bring the desired output.
Jon Skeet is right in his direction that inner join will do what you want. Considering your question it seems like you need to have inner join with sum of respective row like below. If it is not your requirement then you need to modify your question.
public class Program
{
public static void Main()
{
var left= new List<Product>(){
new Product(){ID=1,Name="A",Qty1=0,Qty2=5},
new Product(){ID=2,Name="B",Qty1=0,Qty2=52}
};
var right= new List<Product>(){
new Product(){ID=1,Name="A",Qty1=57,Qty2=0},
new Product(){ID=2,Name="B",Qty1=84,Qty2=0}
};
var outer=left.Union(right);
Console.WriteLine(outer.Count());//will be four which is not expected.
var query = left.Join(right, d => d.ID, e=> e.ID, (f,g) => new Product(){ID = f.ID, Name = f.Name, Qty1 = f.Qty1+g.Qty1, Qty2 = f.Qty2+g.Qty2});
foreach(var item in query)
{
item.Print();
}
}
}
public class Product {
public int ID{get; set;}
public string Name{get; set;}
public int Qty1{get; set;}
public int Qty2{get; set;}
public void Print()
{
Console.WriteLine("ID : {0}", ID);
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Qty1: {0}", Qty1);
Console.WriteLine("Qty2: {0}", Qty2);
}
}
Here is output from above code:
4
ID : 1
Name: A
Qty1: 57
Qty2: 5
ID : 2
Name: B
Qty1: 84
Qty2: 52
You may modify and test this code here => link

Web API, OData, EF5, Union: The 'Distinct' operation cannot be applied to the collection ResultType of the specified argument

I'm working on a Web API prototype using the OData Nuget package.
I'm having some issues getting a LINQ to EF query to work.
Here are my data model. It has been highly simplified.
I'm trying to get the query to work using this DTO:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
The query looks like this:
[Queryable]
public IQueryable<Product> Get()
{
var productA = _context.ProductA
.Select(p => new Product
{
Id = p.id,
Name = p.name,
Orders = p.ProductAOrders.Select(o => new Order
{
Id = o.OrderId,
Date = o.Orders.Date,
})
});
var productB = _context.ProductB
.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
Orders = p.ProductBOrders.Select(o => new Order
{
Id = o.OrderId,
Date = o.Orders.Date,
})
});
return productA.Union(productB);
}
When trying to Union the two queries I get this error:
<Error><Message>An error has occurred.</Message><ExceptionMessage>The 'Distinct' operation cannot be applied to the collection ResultType of the specified argument.
Parameter name: argument</ExceptionMessage><ExceptionType>System.ArgumentException</ExceptionType><StackTrace> at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateDistinct(DbExpression argument)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnionTranslator.TranslateBinary(ExpressionConverter parent, DbExpression left, DbExpression right)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.BinarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery.ToTraceString()
at System.Data.Entity.Internal.Linq.InternalQuery`1.ToString()
at System.Data.Entity.Infrastructure.DbQuery`1.ToString()
at System.Convert.ToString(Object value, IFormatProvider provider)
at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.<ExecuteAsync>b__2(TraceRecord tr, Object value)
at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<>c__DisplayClass1f.<TraceBeginEndAsync>b__13(TraceRecord traceRecord)
at System.Web.Http.Tracing.SystemDiagnosticsTraceWriter.Trace(HttpRequestMessage request, String category, TraceLevel level, Action`1 traceAction)
at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<TraceBeginEndAsync>b__12(TResult result)
at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass3b`2.<Then>b__3a(Task`1 t)
at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
</StackTrace></Error>
I can return either productA or productB - but returning a Union of these 2 queries result in the distinct error above.
Any ideas to what I might be doing wrong?
Looks like an EF bug. I assume you are trying to get MEST (multiple entity sets of same type) working. Instead of the query that you had, you can try,
public IQueryable<Product> Get()
{
var productA = _context.ProductA
.Select(p => new Product
{
Id = p.id,
Name = p.name,
});
var productB = _context.ProductB
.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
});
return
productA
.Union(productB)
.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
Orders = _context.Orders
.Where(o => o.ProductA.Id == p.Id || o.ProductB.Id == p.Id)
.Select(o => new Order
{
Id = o.OrderId,
Date = o.Orders.Date,
})
});
}
The idea is to take the navigation properties out of the union and add them later back. This would work only if Orders had back pointer to ProductA or ProductB.
This seems to be by design (or a limitation). For set operations (UNION, INTERSECT, EXCEPT) we only allow model types and "flat" transient types (i.e. row types (e.g. created for projections) without collection properties).
The workaround here would be to do the union on the client by enforcing query execution i.e. instead of doing this:
var query3 = query1.Union(query2);
do this:
var query3 = query1.ToList().Union(query2);
Just tried this query... it seems to be the only way using the navigation properties.
var productA = _context.ProductA
.Select(p => new Product
{
Id = p.id,
Name = p.name,
});
var productB = _context.ProductB
.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
});
return
productA
.Union(productB)
.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
Orders = _context.ProductAOrders
.Where(x => x.ProductAId == p.Id)
.Select(o => new Order
{
Id = o.ProductAId,
Date = o.Orders.Date
})
.Union( _context.ProductBOrders
.Where(x => x.ProductBId == p.Id)
.Select(o => new Order
{
Id = o.ProductBId,
Date = o.Orders.Date
}))
});
It result in this error:
<Error><Message>An error has occurred.</Message><ExceptionMessage>The type 'API.Models.Product' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.</ExceptionMessage><ExceptionType>System.NotSupportedException</ExceptionType><StackTrace> at System.Data.Objects.ELinq.ExpressionConverter.ValidateInitializerMetadata(InitializerMetadata metadata)
at System.Data.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery.ToTraceString()
at System.Data.Entity.Internal.Linq.InternalQuery`1.ToString()
at System.Data.Entity.Infrastructure.DbQuery`1.ToString()
at System.Convert.ToString(Object value, IFormatProvider provider)
at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.<ExecuteAsync>b__2(TraceRecord tr, Object value)
at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<>c__DisplayClass1f.<TraceBeginEndAsync>b__13(TraceRecord traceRecord)
at System.Web.Http.Tracing.SystemDiagnosticsTraceWriter.Trace(HttpRequestMessage request, String category, TraceLevel level, Action`1 traceAction)
at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<TraceBeginEndAsync>b__12(TResult result)
at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass3b`2.<Then>b__3a(Task`1 t)
at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)</StackTrace></Error>
I cannot understand why 'API.Models.Product' appears in two structurally incompatible initializations within a single LINQ to Entities query.
If I replace
Orders = _context.ProductAOrders
.Where(x => x.ProductAId == p.Id)
.Select(o => new Order
{
Id = o.ProductAId,
Date = o.Orders.Date
})
.Union( _context.ProductBOrders
.Where(x => x.ProductBId == p.Id)
.Select(o => new Order
{
Id = o.ProductBId,
Date = o.Orders.Date
}))
With this (to make things simpler) I get the same error
Orders = _context.Orders.Select(o => new Order
{
Id = o.Id,
Date = o.Date
})
Seems LINQ to EF is not my best friend these days :)

LINQ GroupBy month

I am having trouble getting an IQueryable list of a (subsonic) object grouped by Month and Year.
Basic view of the object...
public partial class DatabaseObject
{
[SubSonicPrimaryKey]
public int objectID { get; set; }
public string Description { get; set; }
public decimal Value { get; set; }
public string Category { get; set; }
public DateTime DateOccurred { get; set; }
}
Method to get IQueryable in my Database repository...
public IQueryable GetData(string DataType)
{
return (from t in db.All<DatabaseObject>()
orderby t.DateOccurred descending
select t)
.Where(e => e.Category == DataType);
}
My question is, how can I return the dates grouped by Month? I have tried the below, but this results in compiler warnings regarding anonymous types...
public IQueryable GetData(string DataType)
{
var datalist = (from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType);
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l select new
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), // Sum(v => v.Value),
Category = "Grouped"
DateOccurred = l.Last(v => v.DateOccurred)
}
return datalist;
}
Any ideas?
Try this couple issues i found, but you basically need to select a Database object versus anonymous type?
IQueryable<DatabaseObject> datalist = (
from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType)
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l
select new DatabaseObject()
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), //Sum(v => v.Value),
Category = "Grouped",
DateOccurred = l.Max(v => v.DateOccurred)
}).AsQueryable();
Let me know if my solution is now what you want. I also noticed you were using Last? The extension you were using I do not have so I replaced it with Max. I don't have subsonic installed so it might come with the libraries.
Any way don't combine LINQ in query syntax and LINQ in extension methods syntax. Use next:
from t in db.All<DatabaseObject>()
where e.Category equals DataType
orderby t.DateOccurred descending
select t;
The issue is apparantly to do with the way Subsonic interprests certain linq statements and is a known bug.
IEnumerable<DatabaseObject> datalist = (
from t in db.All<FinancialTransaction>().Where(e => e.Category == DataType).ToList()
let m = new
{
month = t.DateOccurred.Month,
year = t.DateOccurred.Year
}
group t by m into l
select new DatabaseObject()
{
Description = string.Format("{0}/{1}", l.Key.month, l.Key.year),
Value = l.Sum(v => v.Value), //Sum(v => v.Value),
Category = "Grouped",
DateOccurred = l.Max(v => v.DateOccurred)
}).AsQueryable();
I have fixed this by declaring an list of type IEnumerable and using ToList() to cast the database interaction, finally the query is then recast AsQueryable()

Resources