Linq does not group in VB.Net - linq

For educational purposes I tried to convert the following Linq expression from the book "Linq in action" into VB.net
Original C#
var list =
from book in SampleData.Books
group book by new { book.Publisher.Name, book.Subject }
into grouping
select new {
Publisher = grouping.Key.Publisher,
Subject = grouping.Key.Subject,
Book = grouping
};
My attempt:
Dim list = _books.GroupBy(Function(book) New With {.Publisher = book.Publisher.Name,
book.Subject}).
Select(Function(grouping) New With {.Publisher = grouping.Key.Publisher,
.Subject = grouping.Key.Subject,
.Books = grouping})
For Each item In list
Console.WriteLine("Publisher:" & item.Publisher & ", Subject:" & item.Subject)
For Each Book In item.Books
Console.WriteLine(" " & Book.Title)
Next
Next
This leads to the following output:
Publisher:FunBooks, Subject:Fun
Funny Stories
Publisher:Joe Publishing, Subject:Work
LINQ rules
Publisher:Joe Publishing, Subject:Work
C# on rails
Publisher:Joe Publishing, Subject:Fun
All your base are belong to us
Publisher:FunBooks, Subject:Fun
Bonjour mon Amour
I expected, that the books "LINQ rules" and "C# on rails" are grouped as well as the books "Funny Stories" and "Bonjour mon Amour" because they have the same Publisher and Subject.
My anonymous key consists a new object of two simple strings.
I already tried to search in SO, but other (or) answers do not solve my problem. Even some code translators like telerik or carlosag are no help in this case.

This is the problem:
GroupBy(Function(book) New With {.Publisher = book.Publisher.Name,
book.Subject})
That's not equivalent to the C# version, because unfortunately VB uses mutable properties in anonymous types by default, and mutable properties aren't considered as part of the hash code or equality operations. You need to make both properties "Key" properties:
GroupBy(Function(book) New With {Key .Publisher = book.Publisher.Name,
Key book.Subject})
Then it should work fine. You can read more about anonymous types in VB on MSDN.

While I applaud your efforts to translate the samples, we actually have all of the samples for LINQ in Action in C# and VB available for download from the Manning Site: http://www.manning.com/marguerie/. Also, we have added samples to the LinqPad samples to make it easy to try the samples and save your changes. See http://www.thinqlinq.com/Default/LINQ-In-Action-Samples-available-in-LINQPad.aspx for instructions on how to access that.
It appears that you are working on example 5.06b. Updating it slightly, our VB translation is:
Dim query = _
From book In SampleData.Books _
Group book.Title By book.Publisher, book.Subject Into grouping = Group _
Select _
Publisher = Publisher.Name, _
Subject = Subject.Name, _
Titles = grouping
If you want to use the Lambda syntax, you do need to specify the Key as #johnskeet indicated:
Dim list = SampleData.Books.GroupBy(Function(book) New With {
Key .Publisher = book.Publisher.Name,
Key .Subject = book.Subject}).
Select(Function(grouping) New With {
.Publisher = grouping.Key.Publisher,
.Subject = grouping.Key.Subject,
.Books = grouping})

Related

What is the performance optimum (or even better coding practise) for writing this Linq query

I am new to linq so please excuse me if I am asking a very basic question:
paymentReceiptViewModel.EntityName = payment.CommitmentPayments.First().Commitment.Entity.GetEntityName();
paymentReceiptViewModel.HofItsId = payment.CommitmentPayments.First().Commitment.Entity.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = payment.CommitmentPayments.First().Commitment.Entity.LocalEntityId;
paymentReceiptViewModel.EntityAddress = payment.CommitmentPayments.First().Commitment.Entity.Address.ToString();
This code is too repetitive and I am sure there is a better way of writing this.
Thanks in advance for looking this up.
Instead of executing query at each line, get commitment entity once:
var commitment = payment.CommitmentPayments.First().Commitment.Entity;
paymentReceiptViewModel.EntityName = commitment.GetEntityName();
paymentReceiptViewModel.HofItsId = commitment.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = commitment.LocalEntityId;
paymentReceiptViewModel.EntityAddress = commitment.Address.ToString();
It depends a bit on what you are selecting to, you cannot select from one entity into another in Linq to Entities. If you are using LINQ to SQL and creating the paymentReceiptModel, you can do this.
var paymentReceiptModel = payment.CommitmentPayments.select(x=>new{
EntityName = x.Commitment.Entity.GetEntityName(),
HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
LocalId = x.Commitments.Entity.LocalEntityId,
EntityAddress = x.Commitment.Entity.Address
}).FirstOrDefault();
If you are using an already instantiated paymentReceiptModel and just need to assign properties then you are better looking to the solution by lazyberezovsky.
To get around the limitation in Linq to Entities, if that is what you are using, you could do this
var result = payment.CommitmentPayments.select(x=>x);
var paymentReceiptModel= result.select(x=>new
{
EntityName = x.Commitment.Entity.GetEntityName(),
HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
LocalId = x.Commitments.Entity.LocalEntityId,
EntityAddress = x.Commitment.Entity.Address
}).FirstOrDefault();
This essentially, makes the majority of your query Linq to Objects, only the first line is Linq to Entities

LINQ to sharepoint . join list help

I am currently using SharePoint 2010,and in my business layer I am using LINQ to SharePoint. I generated all my Entity classes using SPMetal.
We are creating a Library system, my system has 2 Lists . The first one is Contribution and the second one is Contributor. Each Contributor contains a reference to the Contribution List (a PrimaryISBN reference). The Contribution List contains list of books and PrimaryISBN is not unique in this list.
Contribution
ID PrimaryISBN TITLE
1 PRIM1 HardcoverLOTR
2 PRIM1 AudioBookLOTR
3 PRIM2 HardcoverHP
Contributor
ID Name PrimaryISBNLookup
1 ABC PRIM1
2 DEF PRIM2
I am currently trying to fetch All the Books Contributed by a Particular user based on the Name.
My query is something like this
var result = from _contributor in data.contributor
where _contributor.Name= "ABC"
select new Book
{
Title = contributor.PrimaryISBNLookup.Title
}
The problem that I am currently facing is in retrieving records that have same ISBN but different title (Each format will have a title i.e. a Audio book will have a title and a Hardcover of the same book will have a different one).
This query returns me only 1 records even thought I have 2 records in my system i.e. the record with ID (in Contribution) that I am forced to insert during the insertion of record into Contributor List.
Your help is highly appreciated.
From what I understand, you try to implement a simple join, like this:
var results = from _contributor in data.contributor
join _contribution in data.contribution
on _contributor.PrimaryISBNLookup equals _contribution.PrimaryISBN
where _contributor.Name == "ABC"
select new Book
{
Title = _contribution.Title
}
If you want to use DataTable in SPList, try this:
SPList cList = spWeb.Lists.TryGetList("Customer");
SPList oList = spWeb.Lists.TryGetList("Order");
DataTable cTable= cList.Items.GetDataTable();
DataTable oTable= oList.Items.GetDataTable();
var coList = from tbl1 in cTable.AsEnumerable()
join tbl2 in oTable.AsEnumerable() on tbl1["Title"] equals tbl2["CustomerName"]
select new
{
ItemName = tbl2["Title"],
CustomerName = tbl1["Title"],
Mobile = tbl1["MobileNo"]
};

Can't combine "LINQ Join" with other tables

The main problem is that I recieve the following message:
"base {System.SystemException} = {"Unable to create a constant value of type 'BokButik1.Models.Book-Author'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."}"
based on this LinQ code:
IBookRepository myIBookRepository = new BookRepository();
var allBooks = myIBookRepository.HamtaAllaBocker();
IBok_ForfattareRepository myIBok_ForfattareRepository = new Bok_ForfattareRepository();
var Book-Authors =
myIBok_ForfattareRepository.HamtaAllaBok_ForfattareNummer();
var q =
from booknn in allBooks
join Book-Authornn in Book-Authors on booknn.BookID equals
Book-Authornn.BookID
select new { booknn.title, Book-AuthorID };
How shall I solve this problem to get a class instance that contain with property title and Book-AuthorID?
// Fullmetalboy
I also have tried making some dummy by using "allbooks" relation with Code Samples from the address http://www.hookedonlinq.com/JoinOperator.ashx. Unfortunately, still same problem.
I also have taken account to Int32 due to entity framework http://msdn.microsoft.com/en-us/library/bb896317.aspx. Unfortunatley, still same problem.
Using database with 3 tables and one of them is a many to many relationship. This database is used in relation with entity framework
Book-Author
Book-Author (int)
BookID (int)
Forfattare (int)
Book
BookID (int)
title (string)
etc etc etc
It appears that you are using two separate linq-to-sql repositories to join against. This won't work. Joins can only work between tables defined in a single repository.
However, if you are happy to bring all of the data into memory then it is very easy to make your code work. Try this:
var myIBookRepository = new BookRepository();
var myIBok_ForfattareRepository = new Bok_ForfattareRepository();
var allBooks =
myIBookRepository.HamtaAllaBocker().ToArray();
var Book_Authors =
myIBok_ForfattareRepository.HamtaAllaBok_ForfattareNummer().ToArray();
var q =
from booknn in allBooks
join Book_Authornn in Book_Authors
on booknn.BookID equals Book_Authornn.BookID
select new { booknn.title, Book_AuthorID = Book_Authornn.Book_Author };
Note the inclusion of the two .ToArray() calls.
I had to fix some of you variable names and I made a bit of a guess on getting the Author ID.
Does this work for you?
I would suggest only having a single repository and allowing normal joining to occur - loading all objects into memory can be expensive.
If you are making custom repositories you make also consider making a custom method that returns the title and author IDs as a defined class rather than as anonymous classes. Makes for better testability.

Linq Compiled Queries and int[] as parameter

I'm using the following LINQ to SQL compiled query.
private static Func<MyDataContext, int[], int> MainSearchQuery =
CompiledQuery.Compile((MyDataContext db, int[] online ) =>
(from u in db.Users where online.Contains(u.username)
select u));
I know it is not possible to use sequence input paramter for a compiled query and im getting “Parameters cannot be sequences” error when running it.
On another post here related , I saw that there is some solution but I couldn't understand it.
Does anyone know to use complied query with array as input paramter?
Please post example if you do.
Like the post that you referenced, it's not really possible out of the box. The post also references creating your own query provider, but it's a bit of overhead and complexity that you probably don't need.
You have a few options here:
Don't use a compiled query. Rather, have a method which will create a where clause from each item in the array resulting in something like this (psuedo-code):
where
online[0] == u.username ||
online[1] == u.username ||
...
online[n] == u.username
Note that you would have to use expression here to create each OR clause.
If you are using SQL Server 2008, create a scalar valued function which will take a table-valued parameter and a value to compare againt. It will return a bit (to indicate if the item is in the values in the table). Then expose that function through LINQ-to-SQL on your data context. From there, you should be able to create a CompiledQuery for that. Note that in this case, you should take an IEnumerable<string> (assuming username is of type string) instead of an array, just because you might have more than one way of representing a sequence of strings, and to SQL server for this operation, it won't matter what the order is.
One solution that I have found myself doing (for MS SQL 2005/2008). And I'm not sure if it is appropriate in all scenarios is to just write dynamic sql and execute it against the datacontext using the ExecuteQuery method.
For example, if I have an unbounded list that I am trying to pass to a query to do a contains...
' Mock a list of values
Dim ids as New List(of Integer)
ids.Add(1)
ids.Add(2)
' ....
ids.Add(1234)
Dim indivs = (From c In context.Individuals _
Where ids.Contains(c.Id) _
Select c).ToList
I would modify this query to create a SQL string to execute against the database directly like so...
Dim str As New Text.StringBuilder("")
Dim declareStmt as string = "declare #ids table (indivId int) " & vbcrlf)
For i As Integer = 0 To ids.Count - 1
str.Append("select " & ids(i).ToString() & " & vbcrlf)
If i < ids.Count Then
str.Append("union " & vbcrlf)
End If
Next
Dim selStatement As String = "select * From " & context.Mapping.GetTable(GetType(Individuals)).TableName & _
" indiv " & vbcrlf & _
" inner join #ids ids on indiv.id = ids.id"
Dim query = declareStmt & str.ToString & selStatement
Dim result = context.ExecuteQuery(of Individual)(query).ToList
So barring any syntax errors or bugs that I coded (the above is more or less psuedo code and not tested), the above will generate a table variable in SQL and execute an inner join against the desired table (Individuals in this example) and avoid the use of a "IN" statement.
Hope that helps someone out!

rss feed by linq

I am trying to extract the rss feed using linq. Thought it would be simple, but its is not returning any nodes. probably i have to go the channel/item node, but don't know how.
Dim rssUrl As String = "http://webclip.in/rss.aspx?u=mostliked"
Dim rssDoc As XDocument = XDocument.Load(rssUrl)
Dim rssResultSet = From node In rssDoc.Descendants("item") _
Select New With { _
.title = node.Element("title").Value, _
.link = node.Element("link").Value, _
.description = node.Element("description").Value, _
.pubDate = Date.Parse(node.Element("pubdate").Value) _
}
DataGridView1.DataSource = rssResultSet
Two issues here... First, you should correct this line:
.pubDate = Date.Parse(node.Element("pubDate").Value)
The pubDate is a case-sensitive node in XML. Secondly, your dataSource will never work because LINQ is lazy computation. You have to use ToList() or a similar method that enumerate your collection. If you debug within Visual Studio 2010, you'll see that rssResultSet does not have a value because it is only enumerated when your code calls for it. Replace with this:
DataGridView1.DataSource = rssResultSet.ToList()
My last piece of advice is to set your DataGrid to AutoGenerate it's columns.
the casing on pubdate is wrong. It should be "pubDate". otherwise, works fine.

Resources