Loading Record By Predicate / Lambda Via LINQ

Jan 12, 2011

I am pretty confused about lambdas. What I am trying to do here is write a function that will return an object from a certain table with a certain criteria. So lets say I can write:
function GetRecord(TableName as string,Criteria as string) as object
'do the linq-stuff
end function

Now I don't care if the parameters are strings or lambdas or whatever, but the end result must be that at runtime I don't know which table and which criteria will be used. As sometimes I need to get a customer record by email and sometimes a product by id etc. If possible I would prefer returning a list of matching objects and then I would just use .firstordefault when I want 1 (such as by id...).

View 2 Replies


ADVERTISEMENT

Convert Lambda Expression In OrderBy Predicate From C#

Apr 24, 2012

I've got the following to sort entities by their job position. The desired order ist defined in another array. In C# this code works:[code]However I will have to convert this to VB.net. I read the equivalent would be something like the following:[code]This does not compile, gives me "Expression expected" right after the Function(x). What am I doing wrong?

View 1 Replies

Asp.net - Complex Linq Query - Add A .Where() Or .Any() Predicate To Reduce Query Complexity (in VB)?

Sep 14, 2010

I have to join two main tables, and I need to filter the results by elements in an ASP.NET web form. These filters are created on the fly so I have to use a lot of where extensions to filter the query. I want to execute the query with as optimized SQL as possible.

I am first doing a simple join between TW_Sites and TW_Investigators. Then there are two sub-tables that are involved. TW_InvestigatorToArea and TW_InvestigatorToDisease. While most of the where clauses are working fine, I have found a performance issue that won't be an issue right now, but will be an issue as the table gets bigger.

The arrays DiseaseCategories and DiseaseAreas would be the results of a CheckBoxList result.

Protected Sub LoadResults()
'Get Dictionary of Filters
Dim FilterDictionary As OrderedDictionary = Session.Item("InvestigatorFilterDictionary")
' Initialize LinqToSql

[code]....

View 2 Replies

Why Does Linq Lambda Work One Way But Not The Other

Dec 7, 2011

I am learning MVC3 and transitioning to VB.NET from C# at the same time (Fun, I know). I am running through the MvcMusicStore sample for learning MVC3. All the samples are in C# so I am converting them to VB. I came across one piece of code that I was unable to directly convert and had to change slightly to get it to work.

why one way works and the other doesn't.

This does not work:

Dim albums = New List(Of Album)() From { _
New Album() With { _
.Title = "A Copland Celebration, Vol. I", _

[Code].....

View 2 Replies

Linq Doing A Group In A Lambda Subselect

Feb 23, 2012

I have a user input screen that allows them to select input values and the resulting query is dependent on which values the user entered. The resulting query groups up the results to present a list of unique customers

Simplified table design - A customer can be in many states
[code...]

View 1 Replies

Linq - Entity Framework Many-to-many Using Lambda

Feb 11, 2010

I'm using Entity Framework in Visual Studio 2010 Beta 2 (.NET framework 4.0 Beta 2). I have created an entity framework .edmx model from my database and I have a handful of many-to-many relationships.

A trivial example of my database schema is

Roles (ID, Name, Active)
Members (ID, DateOfBirth, DateCreated)
RoleMembership(RoleID, MemberID)

[Code]....

For brevity I turned the list of all the columns from the Members table into *

As you can see it's just ignoring the "Role" query.

View 2 Replies

Linq - Examples Of .NET Lambda Expression?

Feb 3, 2011

Where can I find complex LINQ examples made using VB.NET Lambda Expression syntax?During my searches I always found 101 LINQ Samples but they use the other notation and for me is not always clear how to transform that code into a lambda expression.

View 1 Replies

LINQ - Calculate Variance With Lambda Expression

Feb 3, 2011

I am trying to convert the following code for the variance calculation
public static double Variance(this IEnumerable<double> source){
double avg = source.Average();
double d = source.Aggregate(0.0,
(total, next) => total += Math.Pow(next - avg, 2));
return d / (source.Count() - 1);
}
Described on CodeProject into corresponded VB.NET lambda expression syntax, but I am stuck in the conversion of Aggregate function. How can I implement that code in VB.NET?

View 1 Replies

Linq - Write Lambda Select Method In .net?

May 22, 2012

For I've tried this:Dim exampleItems As Dictionary(Of String, String) = New Dictionary(Of String, String)
Dim blah = exampleItems.Select (Function(x) New (x.Key, x.Value)).ToList 'error here

But I'm getting a syntax error and all the examples that I've seen are in C#.

View 1 Replies

Pass A Lambda Function To Linq's Orderby?

Jan 24, 2010

I am trying to pass a lambda function to Linq's orderby and cannot get it to work.

The relevant code is:

Dim myordering = Function(m) m.Count
If isAlphaOrder Then
myOrdering = Function(m) m.Key 'Order by Alphabet

[Code].....

View 4 Replies

Set An Indexing Variable In Linq/Lambda Expression?

Apr 16, 2010

I have a lambda expression that builds a list ofanonymous types. I would like to include a property in the anonymous type that is a counter. So the first entry is 1, second 2, third 3, and so on.I thought I recallenyone know the syntax for defining an indexing variable as part of a Linq query or lambda expression?

View 10 Replies

Linq - Order By Multiple Columns Using Lambda Expressions

Nov 16, 2009

I'm still trying to get my head around the whole "Lambda Expressions" thing.

Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?

Here is my existing code, which returns an ordered list using a single-column to order the results:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList

Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.

I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList

View 2 Replies

VB Dynamic Run-Time Query With Linq And Lambda Expressions

Mar 16, 2009

I have an untyped dataset returned from my WebService. The user wants to dynamically construct a query referencing tables and columns and specifying values to test for.I have looked at Lambda Expressions and the Expressions.Expression Namespace. I think these provide the answer I'm looking for, but I'm not certain how to go about contructing the linq expressions to extract the datarows I'm looking for.

I plan on limiting the result to one datatable that the query will result in and i"ll provide the joins from the user's constructs.For a simple example I have a DataTable with (n) rows called "Table", and in it there is a computed column called "b_IsActive" that has the expression "Convert(IsActive, 'System.Boolean')". The user wants to retrieve all rows in "Table" where field "b_IsActive" is true.

View 5 Replies

Book Recommendation With Good Lambda Expressions And LINQ Chapters?

May 20, 2009

I'm looking for an advanced level VB.NET book which covers LINQ and Lambda Expressions.Generally I read C# .NET books due to lack of good VB.NET books when it comes to generic .NET Framework related subjects. However Lambda and LINQ is quite different in C# and VB.NET I'm looking for an advanced level VB.NET book on this subjec

View 1 Replies

Order A Collection Based On A Child Property Using LINQ Or A Lambda?

Jan 26, 2012

I get the following string expression provided:"ChildObject.FullName" ...where ChildObject is an instance property on the MyObject1 type.ChildObject has a property named "FullName" and I want to sort a collection of type "MyObject1" based on this child properties "FullName" value.

I can do this all day long on properties directly on MyObject1 but I run into 2 challanges when doing it on a child instance and I can't get all the pieces working. The main 2 challanges are:

MyObject1 has a few different child property types so I can't hardcode the type for ChildObject. The string could be of any type.The sort expression is a String and not a known type.Above the value returned from the last line in the expression (if I run the code outsode the OrderBy method, does provide me the 'FullName' information I need. So the code must be close, but it still does not work.

Any ideas on how I can accomplish this? What I am trying to prevent is hardcoding a series of 'If' blocks on the child's type to then hardcode in its type to the sort or OrderBy method.

View 2 Replies

Can A LINQ Or A LAMBDA Expression Be Used To Count The 1's In A Binary String Or Char Array

Sep 15, 2010

Can a LINQ or a LAMBDA expression be used to count the 1's in a binary string ?For example, if I convert a number to its BINARY using.>>

Dim binaryString As String = Convert.ToString( numberVariable, 2 )

1) Without using a loop such as a FOR NEXT loop, can I count the number of 1's in the STRING using LINQ or a LAMBDA expression?

2) Can I get the indexes of where the 1's are at in a collection such as a LIST using LINQ or a LAMBDA expression?I know the syntax of some LINQ expressions, however, I don't know which method may be suitable.

View 2 Replies

Nested Multi-line Lambda Function As Parameter For LINQ Select Is Causing An Error

Jun 29, 2010

I'm trying to use a nested multi-line lambda Function in VB.NET and am getting an error. Here's what my code looks like:

cartItems = cartItems.Select(Function(ci) New With {.CartItem = ci, .Discount = discountItems.FirstOrDefault(Function(di) di.SKU = ci.SKU)})
.Select(Function(k)
If k.Discount Is Not Nothing Then

[code]....

View 2 Replies

Lambda Coding - Basic Code Of Lambda With Explanation

Jun 21, 2011

Im hearing about this, can someone explain it to me or please show some basic code of Lambda with explanation.

View 2 Replies

Lambda Tutorial And Solving A Lambda-Function

Dec 14, 2009

Is it possible to shorten the following function to a lambda expression?Or (to do the trick by myself) what is the best and most understandable for beginners tutorial for lambda in vb.net?[code]

View 2 Replies

Loading A Xml Document From A File Built Use Linq.Xelement

Jan 11, 2012

I'm trying to load in a xml file that was build using another windows form, but when I try the xml document I get the following error: Name cannot begin with the '%' character, hexadecimal value 0x25. Line 10, position 13.[code]

View 3 Replies

Add A Record To Database With LINQ?

Mar 2, 2009

I have been utilizing Scott Gu's tutorials on LINQ to SQL to try to learn some LINQ. I have been able to view, retrieve, and update records but I am unable to write new records into the database (MSSQL). Scott starts getting into inserting rows in the fourth section of the set of tutorials. As you can see on that page (or may already know), in order to add a record you must do the following (VB.NET)[code]...

View 1 Replies

SQL - How To Insert New Record Through LINQ

Aug 1, 2011

I am trying to insert a new record though linq. I am able to update and read data with out any problem, but how to just inset a new record. Here is a start of my function.

Public Function AddAddressInfo(ByVal objdeptGUID As String, ByVal objGEOCode As String, ByVal objArressCommonName As String, ByVal objStreetAddress As String, ByVal objAddressNotes As String, ByVal objIsPublic As Boolean, ByVal objSesionToken As String)
''#Check of Token is good
If CheckToken(objSesionToken, objdeptGUID) = False Then
Return "Error"
End If
[Code] .....

View 1 Replies

Searching The Database Record Using LINQ

Aug 3, 2010

How can search record in my DataSet (fields: Name, Address, Phone#) for a certain name, given by user by clicking a combo box?

View 3 Replies

.net - Update Students Table Record Using LINQ To SQL?

Aug 22, 2011

I´m trying to update my Students table record using LINQ to SQL. The problem is when one of the Properties of the object changed and 'PropertyChanging' Event is fired using 'SendPropertyChanging()' method.

student_id is a PK
data types are matched

Here is the full ArgumentException:

GenericArguments[2], 'System.String', on
'System.Data.Linq.Mapping.PropertyAccessor+Accessor`3[T,V,V2]'
violates the constraint of type 'V2'.

[code]....

View 1 Replies

Adding Name And Score Record - Insert With LINQ

Apr 22, 2010

What I have is a database in a Windows Form (via tableAdapters etc., basically the default stuff VS adds). What I need to do, is add a very simple record of a name and score (the "place" is an auto-number). I have not even been able to tackle sorting the table, because I can not even figure out how to insert...

View 8 Replies

Asp.net - Using LINQ And A Dropdownlist To Enter A New Record Into An SQL Database

Apr 19, 2012

Our remit is to make a Veterinary Surgery Booking System.

I have an asp.net page that has 4 fields, one of the fields is populated on page load as per the vb code below.

I'm trying to get the selected value (or text) of the dropdownlist control and use it as the value for the first field in the record however every time I select the second or third value in the dropdownlist and click the submit button the new record that is created is inserting the first value in the dropdownlist.[CODE...]

View 2 Replies

Pass Content To Specific Record In XML Using LINQ?

Nov 14, 2009

I am using the following line of LINQ to drill down into an element. Is it possible to expands this code to drill further down so that I can add content to the <population> element in "Test2". I want to be able to do somthing like element.SetValue(1000000). However I need to expand the code below so that I can pass the entire query results into the variable called "element"'

Dim eles = From c In doc.Descendants("File") _
Where c.Attribute("Name").Value = "Test2" _
Select c

[code]....

View 3 Replies

Return Max Record Count By Grouping In Linq?

Nov 9, 2011

I'm very new to linq and I'm trying to come up with a linq query against a dataset that will return a max count value based on grouping records.[code]...

View 1 Replies

DB/Reporting :: Display Single Record From Linq Query?

Mar 24, 2011

For a school programming project we are supposed to create a database with 2 tables country, and continent.then we populate country with every country name, population and continentID. For continent we populate with each continent name.

i have completed this step, and i am able to run a linq query to display all countries and corresponding continent into a datagridview. My problem arises because we are supposed to display each record one at a time, and be able to cycle through one at a time. I cannot for the life of me figure out how to do this.

for example if i made a query to select all countries in africa, i want to beable to display the name of the country, and population in textboxes. then have a next button that will go to the next record.

View 2 Replies

LINQ Insert Child Record Specified Cast Is Not Valid?

Mar 10, 2011

ok I have a weird issue. I created a master record in the master table and then a record in the detail table. when creating the detail record i get a Specified cast is not valid error. Now another weird thing is that once I create the master record I can't query and verify it was created. But when i got to sql management studio I can see the master record. Below is my two procedures and the table definitions. Master table primary key is INVNUM child table primary key it INVLIN_ID and the reference key is INVNUM

View 13 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved