linq

Map two lists into a dictionary in C#

Given two IEnumerables of the same size, how can I convert it to a Dictionary using Linq? IEnumerable<string> keys = new List<string>() { "A", "B", "C" }; IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" }; var dictionary = /* Linq ? */; And the expected output is: A: Val A B: Val B C: Val C I wonder if ...

How do you generate SQL using LINQ?

I want to be able to take a LINQ statement like this. var User = from u in Users where u.UserID == 7 select u.UserName; And have it generate SQL like this. SELECT UserName FROM Users WHERE Users.UserID = 7 I know LINQ TO SQL does this but I don't want all that added xml mapping and generated code. Obviously thi...

Cannot assign LINQ query to variable

I want to declare a variable to hold the query result from LINQ to SQL like to the following: Dim query As IQueryable(Of Student) If isNoUserName Then query = From st In db.Students _ Order By st.AssignedId Ascending _ Where (st.studentId = studentId _ Select st Else...

any reason to not use a dictionary

I was having a discussion with a co-worker over whether it is better to use a Dictionary and repopulate it whenever a result set changes or to just use linq loop over all elements in the list each time. We're trying to map a parent / child relationship, and I suggested using the ParentID as the dictionary key, and the dictionary value a...

selecting a distinct count from LINQ Stored Proc

Hi there I have a stored proc that returns a resultset thus: testID(guid), testName, outcomeID(guid), outcomeName - fields testGuid1, testName1, OutcomeGuid1, outcome1 testGuid1, testName1, OutcomeGuid2, outcome2 testGuid1, testName1, OutcomeGuid3, outcome3 testGuid1, testName1, OutcomeGuid4, outcome4 testGuid1, testName1, Outcome...

Linq read XML doc with missing nodes

Hi I want to read an XML document but it may have some of the node missing and if so I want to use a defualt value for the missing nodes. XDocument xmlDoc = XDocument.Load(Path.Combine(Application.StartupPath, "queues.xml")); var q = from c in xmlDoc.Root.Descendants("Queue") select new Queue {...

Copy values to an array based on half hourly time.

Hi, I'm receiving a bunch of values from my server for various dates with each value corresponding to half hour of a day,i.e for today there will be 50 values...it'll be a basic keyvalue pair like the one below valsFromServer[28/10/2010 00:00:00] = 23; valsFromServer[28/10/2010 00:30:00] = 100; valsFromServer[28/10/2010 01:...

better way to do this foreach using linq

Hey there, I have this foreach loop that doesnt work 100%. Basically I am outputting a string. My problem is I dont want sb.Append(","); to be added the last record in the loop. IS there an easy way using linq to solve this? sb.Append("Readings:["); foreach (var reading in lake.Reading) { ...

How to code an Or extension method

I want to do var testData = new[] { "aap", "aal", "noot", "mies", "wim", "zus", "jet" }; bool result = testData.Or(s => s.Contains("z")); but there is no 'Or' method on IEnumerable. I've tried programming an Or extension method using public static class extensions { public static bool Or<TSource>(this IEnumerable<TSource> sourc...

Grouping & Sorting in linq

I have a list of customer and i need to sort and group the list according to business rule. Group by Customer Name Sort by Customer Name in alphabetical order if there are several results for the same name, then they need to sorted by date of birth in ascending order (the oldest is listed first) Below is the entity. public class Cu...

.NET check if two IEnumerable<T> have the same elements

Possible Duplicate: Comparing two collections for equality I need to verify if two IEnumerable<T> lists have the same elements, not necessarily in the same order. I'm targetting .NET 3.5. Here are the tests. The question is, how should HasSameElements() be implemented? var l1 = new[]{1,2,3}; var l2 = new[]{3,1,2}; bool rez...

How can I dynamically create the condition clause for a LINQ where clause (generic type and dynamic property)

Here is my code: I thought using DLink I should be able to pass the where clause as string expressions however the FindFirstOrDefault doesn't work. Basically, I want the FindFirstOrDefault to be generic so I can pass any object, its key property and value and it should find it. Any ideas? <TestMethod()> Public Sub TestExpression() D...

Using LINQ to query a collection of objects

I have the following that selects a list of benefits for a given product: foreach (var benefit in Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.HeadlineBenefit == false)) However I want to change this to select a list of befits for the first product in the collection. I thought the below woul...

Converting Foreach Loop to Linq and getting error

I've currently got the following foreach loop: List<SearchResult> searchResults = new List<SearchResult>(); foreach (Transmission trans in Results) { searchResults.Add(new SearchResult(trans)); } return searchResults; And I'd like to convert this to a Linq expression, I've tried the following which looks like it achieve the same t...

Can we initialize an object/collection using LINQ in JSON-like syntax?

Can we do something like this or something similar? var staffs = { "Staff": [ { "ID" : 1, "Name" : "John" }, { "ID" : 2, "Name" : "Mark"} ] }; foreach (var staff in staffs) { Console.WriteLine("ID: {0}", staff.ID); Console.WriteLine("Name:...

Problem with retrieving data from xml by linq

I have xml from I want get some data XDocument loaded = XDocument.Load(@"c:\TERC.xml"); var query = (from c in loaded.Descendants("catalog") from r in c.Descendants("row") select (string)r.Element("Name")); this returns me collection of null How can I fix it ? Here is this xml: <?xml vers...

LINQ how to query if a value is between a list of ranges?

Let's say I have a Person record in a database, and there's an Age field for the person. Now I have a page that allows me to filter for people in certain age ranges. For example, I can choose multiple range selections, such as "0-10", "11-20", "31-40". So in this case, I'd get back a list of people between 0 and 20, as well as 30 to 4...

LINQ performance FAQ

I am trying to get to grips with LINQ. The thing that bothers me most is that even as I understand the syntax better, I don't want to unwittingly sacrifice performance for expressiveness. Are they any good centralized repositories of information or books for 'Effective LINQ' ? Failing that, what is your own personal favourite high-p...

Is LINQ banned in your company?

I work for a large company who develop enterprise applications which are performance oriented. Virtually every line of code is closely scrutinised and optimized as much as possible to ensure the best performance. Company policy dictates that LINQ is strictly banned. This is because it is believed that LINQ has a negative performance im...

C# - how to pass 'out' parameter into lambda expression

I have a method with the following signature: private PropertyInfo getPropertyForDBField(string dbField, out string prettyName) In it, I find the associated value prettyName based on the given dbField. I then want to find all properties, if any, that have the name prettyName, so I'm trying to do the following: IEnumerable<PropertyIn...