C# - Pass Parameters To LINQ To XML Query By Using Lambda Expression?

Aug 17, 2010

I am new to LINQ to XML in .net(C#, asp.net). I want to know more about Lambda expressions. I am using Lambada expression with the following query.

count = FieldRoot.Element("USER").Element("MM")
.Where(a => a.Attribute("ID").Value == MID)
.SelectMany(b => b.Descendants("ABC")).Count();

how the Lambda expression work specially in case of parameters (in the above case a & b) ? What is the basic concept of parameters in Lambda expression ? Can we use the names of the variables defined outside of the query instead of a & b ? which elements a & b represent in the above case represent ? Can we pass parameters from outside in the query ? If we can pass parameters from outside query then how it will be done? If you give me any other example instead of the above query to understand the concept of parameter in Lambda expression.

View 1 Replies

Similar Messages:

ADO.NET :: Does Lambda Have An IN Expression That Works Like Sql

Feb 6, 2011

I have a dictionary with integers representing ProductId's.

I want to get all the Products that are listed in this dictionary. What is the best way of doing this?

I have tried the following which doesnt work:

gvBasket.DataSource = ent.Products.Where(x => x.ProductId in Dic.Keys);

View 9 Replies

DataSource Controls :: Linq To Sql Query / Could Not Translate Expression?

Mar 26, 2010

I have the following LINQ query which works correctly:


The following query, however causes an error:


"Could not translate expression 'Table(t_f2f_event).Where(e => ((e.EVT_START_DATE > Invoke(value(System.Func`1[System.Nullable`1[System.DateTime]]))) && (e.EVT_START_DATE < Invoke(value(System.Func`1[System.Nullable`1[System.DateTime]])))))' into SQL
and could not treat it as a local expression."

View 2 Replies

MVC :: RenderAction With Lambda Expression In MVC 3.0 Preview 1

Sep 29, 2010

i have the following, which works:

@{Html.RenderAction("Detail", "Help", new { pageName = "press" });}
But instead i'd like to use a lambda expression to get away from the string bits. I tried using the following (which is the nearest approximation i could figure based on my limited knowledge of the engine):

@{Html.RenderAction<HelpController>(x => x.Detail("press"));}
But i get the following error:

The non-generic method 'System.Web.Mvc.Html.ChildActionExtensions.RenderAction(System.Web.Mvc.HtmlHelper, string, string, System.Web.Routing.RouteValueDictionary)' cannot be used with type arguments

However, i'm reading in the Apress MVC 2.0 book that it is in fact declared as a method that takes type arguments. Am i missing an assembly reference, or has it not been included in the MVC 3.0 Preview 1 build?

View 3 Replies

How To Update List Using Lambda Expression

Mar 15, 2011

I have two lists. lst contains ViewState Data i.e All the records of the gridview & second lstRank contains the list of integer(i.e ID) for only those records which are marked as checked (i.e Gridview contains a columns for checkbox). Now i want to update the lst bool status depending upon integer ID of lstRank. How it can be achieved by lambda expression

List<Tuple<int, string, bool>> lst = (List<Tuple<int, string,bool>>)ViewState["gvData"];
List<int> lstRank = gvDetails.Rows.OfType<GridViewRow>().Where(s => ((CheckBox)s.FindControl("chkSelect")).Checked)
.Select(s => Convert.ToInt32(((Label)s.FindControl("lblRankCD")).Text)).ToList();

View 1 Replies

ADO.NET :: How To Create A Generic Lambda Expression

Oct 26, 2010

I Use entity framework 4.

Here is my model


Each time I want the text for one of these model, I execute this lambda expression p=> p.LangID == 1

Is it possible to create a generic lambda expression function that all of these model can use.?

View 1 Replies

Lambda Expression Is Slower Than Foreach Statement?

Mar 23, 2011

I did a small experiment to test whether lamdba expression can retrieve faster results than foreach statement. but, Lambda failed


why lambda is slower than foreach. This may be a drawback of lambda expression

View 3 Replies

C# - How To Convert Lambda Expression Output To List

Mar 14, 2011

I am selecting the checked rows from Gridview. To achieve this i have written a lambda expression using dynamic keyword.

var dn = gvLoans.Rows.OfType<dynamic>().Where(s => s.FindControl("chkSelect").Checked == true).Select(s => s.FindControl("lblCD")).ToList();

I want the output of this in List. Can it be achieved by extending the query or i have to write foreach statement.

View 2 Replies

Use A Parameters Value As The Property To Be Selected In A LINQ Query ?

Aug 23, 2010

I am using LINQ-to-Entities and here is my query

public void SomeFunction(string searchField)
var data = from a in dx.SomeTable where [code]...

Now if I had to use the value of the parameter "searchField" as the property to be selected in the where clause then how do I do it ?

i.e I want to assign the value of the parameter "searchField" to the property I am checking in the where clause.

So ... the value of "SomeProperty" in a.SomeProperty must be the value of "searchField". How to do this ?

PS : I dont want a.SomeProperty=searchField. What I want is "SomeProperty" itself to be replaced by the value of "searchField" and then , this has to be checked to see if its equal to 270.

View 2 Replies

C# - How To Use Lambda Expression To Select Different Fields From Field Names

Nov 18, 2010

I need to get two fields from a database table (retrieved using linq-to-sql), one field is a datetime (and is a fixed field) and the other is always a decimal, but the field can be different.

The table holds currency data which is processed twice a day and in different currencies so could have fields such as AM_USD, PM_USD, AM_EUR etc. And I need to get data such as a list of the date against PM_USD or the date against AM_EUR.

I would like to be able to call the data using a lambda expression for example (this is a stripped out example):

data = TableData.Select(x=>new {x.DateTimeAdded, x.[**field name as string**]});

I have been trying to write a function to do this, and am failing dismally.

The closest I have managed is:

private Func<TableData, KeyValuePair<DateTime, decimal>> CreateSelect(string FieldName)
var parameterExp = Expression.Parameter(typeof(TableData), "sel");
var dateParameter = Expression.Parameter(typeof(DateTime), "DateTimeAdded");
var fieldParameter = Expression.Parameter(typeof(decimal), FieldName);
ConstructorInfo constructorInfo = typeof(KeyValuePair<DateTime, decimal>).GetConstructor(new[] { typeof(DateTime), typeof(decimal) });
NewExpression constructExpression = Expression.New(constructorInfo, new ParameterExpression[] { dateParameter, fieldParameter});
var lambda = Expression.Lambda<Func<TableData, KeyValuePair<DateTime, decimal>>>( constructExpression, parameterExp);
return lambda.Compile();

Which fails with "System.InvalidOperationException: Lambda Parameter not in scope".

I'm sure I missing something obvious, or going about it wrong way.

View 2 Replies

ADO.NET :: Finding Lambda Expression Against Entity Framework Collection?

Aug 6, 2010

I'm new to LINQ and EF and I seem to be having trouble working this out.

I have a many-to-many relationship between my Location and Region tables. When adding or editing a Location, my interface allows the user to check any number of related Regions. If they click OK, I need to add any new relationships that were checked, and delete any existing relationships that have been unchecked. My basic code is shown below.

However, this code doesn't work. Lower down, the line location.Regions.Contains(region) returns false even when the location already is related to the region. The issue appears to be because the region is from my populated listbox that was initialized earlier and is no longer part of the current EF context. But if I try and add it, I get an error that there is already a Region with that ID.

It seems like what I want to do is change this line to something like location.Regions.Contains((r) => r.RgnID == region.RgnID) so I'm only testing for a particular ID. But this gives me the error "Cannot convert lambda expression to type 'TrailCalendar.Region' because it is not a delegate type."

I don't understand this error but, either way, I'm not sure how I can test if the relationship already exists without reloading a bunch of data, which I'd like to avoid.

View 1 Replies

.net - Pass Dyanamic Parameters In Ajax Autocompelete Query?

Jun 4, 2010

I am using autocomplete functionality found at http://www.devbridge.com/projects/autocomplete/jquery/. In addition to the text in the autocompelete text box, i would like to pass additional information, like selected states and highways. Following is the code I have. I am getting the text value in the textbox in the MVC action, but not the params. Can you please check what I am doing wrong.

var a = $('.exit-filters div.filters input#Exit').autocomplete2({
serviceUrl: $('.exit-filters input#exit-autocomplete-link').val(),
minChars: 1, [code]....

View 1 Replies

DataSource Controls :: Equivalent Of Group Join In Lambda Expression?

Jun 29, 2010

What will be the equivalent GroupJoin lambda expression in LINQ when I do this.

Dim fruit_salad = (From fruits In _DataContext_Fruits _
Group Join fruitRipe In _DataContext_FruitRipe On fruitRipe.fID Equals fruits.fID Into Group
From fruitty_lecious In Group.DefaultIfEmpty() _


View 5 Replies

SQL Server :: Pivot Query / Unable To Pass Dates As Parameters To Storeprocedure?

Oct 4, 2010

I am using following pivot query but not getting result as single row getting as 4 rows.

One more problem i am unable to pass dates as parameters to storeprocedure something like this

select [@date] .

SELECT 'Forecasted' AS HeadCount,
[8/1/2010], [8/8/2010], [8/15/2010], [8/22/2010]
FROM TblEmpCount) AS SourceTable
FOR StartDate IN ([8/1/2010], [8/8/2010], [8/15/2010], [8/22/2010])
) AS PivotTable;

I am getting result as 4 rows but i want result in single row like this

HeadCount 8/1/2010 8/8/2010 8/15/2010 8/222/2010

Forecasted 191 182 176 169

View 2 Replies

DataSource Controls :: Sql Query - Get Minimum Price When Pass Parameters - Code Is Duplicating Value

Feb 1, 2010

here is my query which is not working properly. I have 5 fields in my table Company, Reseller, Item, Code, Price. How can i get minimum Price when i pass parameters for Code is dublication value

Company Reseller Item Code Price
A A-1 I1 C1 20
B A-21 I2 C2 13
C A-B I1 C1 19

select Company,Reseller,Item,Code,Min(Price) from Table1 where code='C1' order by Code HOW CAN I GET THIS BELOW TYPE OF RESULT

Company Reseller Item Code Price
A A-1 I1 C1 20
C A-B I1 C1 19

View 17 Replies

MVC :: How To Pass Linq To Entities Query Result To View

Apr 1, 2010

i have a new question: i read all the tutorials that i found but i cannot understand how to pass a result of a linq to entities result to the view so that i can display the results. My query is actually in the controller function ot the view, i would now loop the results and display them in the page. How?

View 23 Replies

Forms Data Controls :: Sql To Linq Query / Looking To Translate An SQL Query Into Linq?

May 28, 2010

I'm looking to translate an SQL query into linq

SAQ.UserId =
Usrs.UserId AND Scan.UserId =

I'm not sure how to include the "AND" in the LINQ statement.

View 3 Replies

C# - Error - "Cannot Convert Lambda Expression To Type 'string' Because It Is Not A Delegate Type"

Jun 12, 2010

I get this error: "Cannot convert lambda expression to type 'string' because it is not a delegate type" - keyword select become underlined in blue.


Above code should displays drop list of employees first name and last name in a combo box

View 2 Replies

DataSource Controls :: SqlDataSource And Parameters Query / Trying To Accomplish Is Building Dynamic Query

Aug 22, 2010

1. I have a GridView on my page and it uses sqldatasource with parameterized query. What I want to do is, on page load (where nothing has been selected so no parameter supplied), I want it to query everything (something like SELECT * FROM [this_table]) but since my SelectCommand is something like

SELECT * FROM [this_table] WHERE [this_column] = @someParameters AND [that_column] = @someParameters.

Can I play around with default value to achieve something like that but how ? Now, when the page loads, it doesn't show anything (No Gridview).

2. On my page, I made something like (username, gender, address, and more) and one single search button. That means, no single control enable auto postback. What I am trying to accomplish is building dynamic query

(if username specifed -> SELECT * FROM [this_table] WHERE [username] LIKE @username).

If both username and gender are specified (SELECT * FROM [this_table] WHERE [username] LIKE @username AND [gender] = @gender) and you know the rest. How can I do this using GridView and SqlDataSource ? To my knowledge, I can only specify one SELECT statement in a sqldatasource.

View 11 Replies

ADO.NET :: Dynamic LINQ Query / Use "if Statement" In Linq Query

Feb 11, 2011

I want to use "if statement" in Linq query. How can I do this situation?

For example:

if txtAge.Text=="", I will not use that in Linq Query.

else txtAge.Text!="", I will use that in Linq Query.

View 8 Replies

Regular Expression On Web.config Location Path Attribute (with Parameters)?

Jun 30, 2010

Is there any way of doing something like this?

<location path="/(view|edit)post.aspx?id=[7-9][0-9]+">
<allow roles="AdminPublishers"/>
<deny users="*"/>

Authorization is just an example. I would like to be able to do other things with those locations.

View 1 Replies

ADO.NET :: Build A Linq Query / Linq Random Selection?

Sep 14, 2010

I've build a linq query.But i want a random selection so its not always ID : 1,2,3,4,5,6 How can i randomize this var? I like to bind it to a repeater.//TagCloud:

Random rand = new Random();
var tc1 = from i in JumpTide.cms.menu.GetMenuItems(32)
select new


View 1 Replies

DataSource Controls :: Use Is Null In Query Without Using Parameters For It Or Should Use Parameters For This Field Where Value Is NULL

Jan 21, 2010

here is my code for selectiong some records from db table

string strSql = "select * from mtblNBD where SentTo=@SentTo and InternalStatus Is NULL order by DeadLine desc";
SqlCommand com = new SqlCommand(strSql, con);
com.Parameters.Add("@SentTo", SqlDbType.NVarChar, 50).Value = (string)Session["uname"];

here I am using parameters for SenTo field but not for NULL so it is ok... or should I use parameters for this field where value is NULL , if yes then how can I use parameter for this

View 8 Replies

Pass Value To Replace Reg Expression?

Sep 22, 2010

I am having string there i have replace some characters.var rep =' this the text i have to replace, this is the only one'

var k ='this'

View 1 Replies

DataSource Controls :: How To Convert Sql Query Into Linq Query

Mar 10, 2010

select Groupid,GroupName,onorusername from palgroup where groupid in (select distinct Groupid

View 5 Replies

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