I need to query multiple columns using Linq query and as far as I know I need to use the Curly braces '{}'
I wrote the following query but for some strange reason its printing the opening and closing braces '{}' that's in the statement.
var q = db.table1.Where(n => n.user== USER).Select(n => new { n.Name, n.LastName });
ViewBag.test = q;
In My View
#foreach (var item in ViewBag.test)
{
#item
}
Output:
{ Name = john, LastName=Smith}
{ Name = Mike, LastName=mojie}
Why is it printing the curly braces?!
Because that's the default implementation of ToString for an anonymous type.
You could try:
#(item.Name + " " + item.LastName)
Related
I am trying to recreate the SQL condition of: like '1 %'.
The column in the table contains two sets of values separated by a space. Using StartsWith(glassTag) returns any row where the column starts with '1'. It seems to do a trim on the string before testing the condition. But, if I use StartsWith("1 "), it returns the rows I expect.
What am I doing wrong?
This is a LINQ to Entity question. SqlMethods are not compatible.
the following returns where the Name is: "119 GL-01"
var glassTag = "1 ";
var gItem = await _context.Items.Where(x => x.Name.StartsWith(glassTag) && x.Material.MaterialType.Name.Equals("Glass") && x.JobItems.Any(j => j.Job.Code.Equals(pCode))).ToListAsync();
The code below returns the results I expect
var gItem = await _context.Items.Where(x => x.Name.StartsWith("1 ") && x.Material.MaterialType.Name.Equals("Glass") && x.JobItems.Any(j => j.Job.Code.Equals(pCode))).ToListAsync();
StartsWith simply doesn't work for a variable being passed when looking for spaces at the end.
I have captured the sql being generated by EF.
The code below generates the sql directly below it. When passing a variable to the StartsWith condition, it doesn't use "like". And it creates something that isn't right.
var gItem = _context.Items.Where(x => x.Name.StartsWith(gd.glasstag + " "));
DECLARE #__glassTag_0 nvarchar(4000) = N'1 ';
SELECT [i].[ItemId], [i].[Name]
FROM [Item] AS [i]
WHERE (#__glassTag_0 = N'') OR ([i].[Name] IS NOT NULL AND (LEFT([i].[Name], LEN(#__glassTag_0)) = #__glassTag_0))
The code below generates the sql below it. Note, it uses the "like" condition.
var gItem = _context.Items.Where(x => x.Name.StartsWith("1 "));
SELECT [i].[ItemId], [i].[Name]
FROM [Item] AS [i]
WHERE [i].[Name] IS NOT NULL AND ([i].[Name] LIKE N'1 %')
So, I will be creating a stored procedure to retrieve the data I need. The code will look like this:
var glassTag = gd.glasstag + " ";
var gItem = await _context.Items.FromSqlRaw($"spItemsByGlassTag '{pCode}', '{glassTag}'").ToListAsync();
IList<Item> items = new List<Item>();
items.Add(new Item
{
tag = "{" + Ann + "}",
value = "Anny"
});
items.Add(new Item
{
tag = "{" + John + "}",
value = "Johnny"
});
How can I use Linq to select tag with {John} and replace value with "Jane"?
LINQ is, as the name suggests, more of a query tools. So you can get specific item(s) that you want to modify from a collection using LINQ, but the modification itself is out-of-scope for LINQ.
Assuming that there is always maximum one match to your criteria, you can do as follows :
var john = items.FirstOrDefault(o => o.tag == "{John}");
if(john != null)
{
john.value = "Jane";
}
Otherwise, you can use LINQ Where(o => o.tag == "{John}") to get the target items for modification. But then you'll need to iterate through the result to actually update the value of each matched item.
items.Where(o => o.tag == "{"+John+"}").ToList().ForEach(item =>{
item.value = "Jane";
});
Here is working fiddle
I am new to LINQ, and I wish to convert from one datatype to another in C#, as well as concatenate a string. How would I accomplish this?
For example, what would the SQL statement
SELECT IPv4 = CONVERT(varchar(3), IPv4_octet1) + '.' +
CONVERT(varchar(3), IPv4_octet2) + '.' +
CONVERT(varchar(3), IPv4_octet3) + '.' +
CONVERT(varchar(3), IPv4_octet4) FROM table;
be in LINQ? (The IPv4_octet's are stored as tinyints in the SQL table.)
In this case I suspect you could just write:
var query = data.Select(x => x.IpV4Octet1 + "." +
x.IpV4Octet2 + "." +
x.IpV4Octet3 + "." +
x.IpV4Octet4);
More generally you'd call ToString, e.g.:
// You wouldn't want to actually do this, but...
var query = data.Select(x => x.IpV4Octet1.ToString() + x.IpV4Octet4.ToString());
If you want more control, and you're not using the result in the rest of the query, you may well want to do the formatting on the .NET side - simply use AsEnumerable when you've selected all the information you want from the database, and then do the rest in LINQ to Objects. For example:
var query = db.Select(x => new { x.HostName, x.IpV4Octet1, x.IpV4Octet2,
x.IpV4Octet3, IpV4Octet4 })
.AsEnumerable() // Switch to LINQ to Objects for rest of query
.Select(x => new { x.HostName,
Address = string.Format("{0}.{1}.{2}.{3}"),
x.IpV4Octet1,
x.IpV4Octet2,
x.IpV4Octet3,
x.IpV4Octet4) });
try this:
string ipv4 = string.Join('.',octets.Select(o => o.ToString()).ToArray());
I have a file that I want to read into an array.
string[] allLines = File.ReadAllLines(#"path to file");
I know that I can iterate through the array and find each line that contains a pattern and display the line number and the line itself.
My question is:
Is it possible to do the same thing with LINQ?
Well yes - using the Select() overload that takes an index we can do this by projecting to an anonymous type that contains the line itself as well as its line number:
var targetLines = File.ReadAllLines(#"foo.txt")
.Select((x, i) => new { Line = x, LineNumber = i })
.Where( x => x.Line.Contains("pattern"))
.ToList();
foreach (var line in targetLines)
{
Console.WriteLine("{0} : {1}", line.LineNumber, line.Line);
}
Since the console output is a side effect it should be separate from the LINQ query itself.
Using LINQ is possible. However, since you want the line number as well, the code will likely be more readable by iterating yourself:
const string pattern = "foo";
for (int lineNumber = 1; lineNumber <= allLines.Length; lineNumber++)
{
if (allLines[lineNumber-1].Contains(pattern))
{
Console.WriteLine("{0}. {1}", lineNumber, allLines[i]);
}
}
something like this should work
var result = from line in File.ReadAllLines(#"path")
where line.Substring(0,1) == "a" // put your criteria here
select line
Using the query expression style, the let clause can be easily written. My question is how to use the dot notation style to write a let clause.
Essentially it's a Select (in most cases) which introduces a transparent identifier - via an anonymous type which encapsulates all the currently specified range variables. For example, this query:
string[] names = { "Jon", "Mark" };
var query = from name in names
let length = name.Length
where length > 3
select name + ": " + length;
is translated into something like this:
var query = names.Select(name => new { name, length = name.Length })
.Where(z => z.length > 3)
.Select(z => z.name + ": " z.length);