Dynamic linq backslash in where clause - c#

I use System.Linq.Dynamic to query entities with dynamic 'where' expressions. I'm querying object that has property "newValue" of string type. Exemplary value would be : "{\"ProcessId\":764, \"ProcessLength\":1000}".
I can't use == because I want to find all hits where the property contains "ProcessId:764", regardless on the rest of the string. The thing is, that stored string contains escape sign "\" and double quotes and I can't figure out what it should like exactly..
dbContext.Processes.Where("#newValue.Contains(\"ProcessId\":764\")") brings error, however dbContext.Processes.Where("#newValue.Contains(\":764\")") works correctly. I guess it must be something with backslashes or double quotes in my query but can't figure it out on my own..

There are two things to note here:
If you know at compile time the column that should be queried (i.e., newValue), just use standard Linq: var list = items.Where(i => i.NewValue.Contains("904")).ToList().
If you do want to use dyanmic Linq, What you'd usually want is to apply Where on some column, e.g. Where("SomeColumn.Contains("something")"), or Where("SomeColumn.Contains(#0)", new string[] {"something"}).
So, in your case, this should work: items.Where("newValue.Contains(\"904\")").
Doing Where("#newValue.Contains("something")") doesn't really make sense, since #newValue would be parsed as a string literal. See also this comment on a similiar question.
Here' a quick example:
public static void Main(string[] args)
{
var items = new []
{
new { Id = "1", Title = "ProcessId: 123"},
new { Id = "4", Title = "ProcessId: 456"},
new { Id = "7", Title = "ProcessId: 789"},
}.ToList();
// returns null, because the string "Title" doesn't contain the string "7"
var res1 = items.Where("#0.Contains(\"7\")", new string[] {"Title"}).FirstOrDefault();
// works - returns the 3rd element of the array
var res2a = items.Where("Title.Contains(#0)", new string[] {"ProcessId: 789"}).FirstOrDefault();
var res2b = items.Where("Title.Contains(\"ProcessId: 789\")").FirstOrDefault();
}

#HeyJude Thanks for the effort, but I still can't get it to work. It has somehow gone wronger and now I can't even fetch correct rows giving only ProcessId number..
Let me give you more detailed description of my setup. In the database there's a table with column "NewValue", I use this column to store json string of current (for the time of creating row in the table) representation of some object e.g. object Process. So the column stores for example string of {"ProcessId":904,"ProcessLength":1000}. To fetch this data from db I create collection of table's records: var items = (from l in db.JDE_Logs
join u in db.JDE_Users on l.UserId equals u.UserId
join t in db.JDE_Tenants on l.TenantId equals t.TenantId
where l.TenantId == tenants.FirstOrDefault().TenantId && l.Timestamp >= dFrom && l.Timestamp <= dTo
orderby l.Timestamp descending
select new //ExtLog
{
LogId = l.LogId,
TimeStamp = l.Timestamp,
TenantId = t.TenantId,
TenantName = t.TenantName,
UserId = l.UserId,
UserName = u.Name + " " + u.Surname,
Description = l.Description,
OldValue = l.OldValue,
NewValue = l.NewValue
});. Then I query it to find matching rows for given ProcessId number e.g. query = "#NewValue.Contains(\"904,)\")";
items = items.Where(query);
This should fetch back all records where NewValue column contains the query string, but this doesn't work. It compiles and 'works' but no data are fetched or fetched are only those records where 904 appears later in the string. Sounds stupid but this is what it is.
What should the query string look like to fetch all records containing "ProcessId":904?

Related

ASP.NET Core Linq query for lists

I have this query that was recently changed to allow searches using lists. However, the logic doesn't seem correct. My initial search logic was as follows:
data = data.where(u=>u.location.contains(FilterInput.RepositoryName)).ToList();
This worked for individual inputs and the logic made sense. In the data result, check if location field contains the Input variable
However in order to handle inputs that are lists, I had to change it to the bottom code which is in this Input list, check if the it contains the location field.
The database outputs data as follows:
Output = {arhde, brhje, ckio}
That means my list input is a small section of what the database contains.
FilterInput.RepositoryName = {a,b,c}
data = (from item in dbContext.Documents
join id in initialData
on item.Id equals id.DocumentId
select new DocumentsListViewModel
{
Id = item.Id,
Name = item.Name,
ApplicationName = item.ApplicationName,
ApplicationSecretKey = item.ApplicationSecretKey,
Link = item.Link,
Location = item.Location,
FileType = item.FileType,
CreatedOn = item.CreatedOn
}).ToList();
if (FilterInput.RepositoryName.Count>0)
{
data = data.Where(u => FilterInput.RepositoryName.Contains(u.Location)).ToList();
}
I don't know if its possible to change this logic to use the first one but accomodate lists as well?

Lambda SQL Query / Manipulate String At Query Or After Result

I'm using C#, EF5, and Lambda style queries against SQL.
I have the usual scenario of binding data to gridviews. Some of the results for my columns may be too long (character count) and so I only want to display the first 'n' characters. Let's say 10 characters for this example. When I truncate a result, I'd like to indicate this by appending "...". So, let's say the following last names are returned:
Mercer, Smith, Garcia-Jones
I'd like them to be returned like this:
Mercer, Smith, Garcia-Jon...
I was doing something like this:
using (var context = new iaiEntityConnection())
{
var query = context.applications.Where(c => c.id == applicationPrimaryKey);
var results = query.ToList();
foreach (var row in results)
{
if (row.employerName.Length > 10)
{
row.employerName = row.employerName.Substring(0, Math.Min(10, row.employerName.ToString().Length)) + "...";
}
if (row.jobTitle.Length > 10)
{
row.jobTitle = row.jobTitle.Substring(0, Math.Min(10, row.jobTitle.ToString().Length)) + "...";
}
}
gdvWorkHistory.DataSource = results;
gdvWorkHistory.DataBind();
However, if I change my query to select specific columns like this:
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
c.applicationCategoryLong,
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})
The result appears to become read-only if specific columns are selected, and I really should be selecting just the columns I need. I'm losing my ability to edit the result set.
So, I'm rethinking the entire approach. There must be away to select the first 'n' characters on select, right? Is there anyway to append the "..." if the length is > 10 on select? That seems trickier. Also, I guess I could parse through the gridview after bind and make this adjustment. Or, perhaps there is a way to maintain my ability to edit the result set when selecting specific columns?
I welcome your thoughts. Thanks!
To quote MSDN
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
So you would have to define a class and select into that if you want read write capability.
e.g.
public class MyClass {
public int id { get; set; }
public string applicationCode {get; set; }
// rest of property defintions.
}
var query2 = context.applications.Select(c => new MyClass {
id = c.id,
applicationCode = c.applicationCode,
// Rest of assignments
};
As to just providing 10 character limit with ... appended. I'm going to assume you mean on the applicationcategoryLog field but you can use the same logic on other fields.
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
applicationCategoryLong = (c.applicationCategoryLong ?? string.Empty).Length <= 10 ?
c.applicationCategoryLong :
c.applicationCategoryLong.Substring(0,10) + "...",
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})

Search values only from first element in linq c#.net

I have the problem in where condition please check this
<Uni_Details Uni_ID="U001" User_Mode="New">
<Uni_Name>
<Full_Name>Asian</Full_Name>
<Short_Name />
</Uni_Name>
<Asc_Uni>
<Asc_Details Asc_Name="Stafford">
<Asc_Add>fsfadfsdfsdfsdf</Asc_Add>
<Asc_Tel>+44 34234234234</Asc_Tel>
<Asc_Country>United Kingdom</Asc_Country>
<Asc_Web>www.ac.lk</Asc_Web>
</Asc_Details>
</Asc_Uni>
<Branch>
<Branch_Details Branch_Name="Head Office">
<Branch_Add>dasdasdadsd</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 342432423</Branch_Tel>
</Branch_Details>
<Branch_Details Branch_Name="Access Tower">
<Branch_Add>dfgdfgdfgdf</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 342432453</Branch_Tel>
</Branch_Details>
</Branch>
<Uni_EMail>info#apiit.lk</Uni_EMail>
<Uni_Web>www.apiit.lk</Uni_Web>
<Course_Data>
<Course_Details Course_ID="U001C001">
<Course_Name>Computer Course</Course_Name>
<Course_Qual>Pass O/L</Course_Qual>
<Course_Dur>3 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>C#.net</Course_Conent_List>
<Course_Conent_List>VB.Net</Course_Conent_List>
<Course_Conent_List>Design Practices</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">5000.00</Fee_Amount>
<Fee_Comment>Onwards</Fee_Comment>
</Course_Fee>
<Course_Desc>Learn Basic Programming practices</Course_Desc>
<Course_Next>Next October</Course_Next>
<Category_List>
<Cat_ID>2</Cat_ID>
<Cat_ID>1</Cat_ID>
</Category_List>
</Course_Details>
</Course_Data>
</Uni_Details>
<Uni_Details Uni_ID="U002" User_Mode="New">
<Uni_Name>
<Full_Name>American College</Full_Name>
<Short_Name>AC</Short_Name>
</Uni_Name>
<Asc_Uni>
<Asc_Details Asc_Name="American College USA">
<Asc_Add>fasdfsdfsdfsdsdfs</Asc_Add>
<Asc_Tel>+94 112 230623</Asc_Tel>
<Asc_Country>United States</Asc_Country>
<Asc_Web>www.ac.lk</Asc_Web>
</Asc_Details>
</Asc_Uni>
<Branch>
<Branch_Details Branch_Name="Head Office">
<Branch_Add>FFSDFASDFSDF</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 112 230623</Branch_Tel>
</Branch_Details>
</Branch>
<Uni_EMail>info#ac.lk</Uni_EMail>
<Uni_Web>www.ac.lk</Uni_Web>
<Course_Data>
<Course_Details Course_ID="U002C0001">
<Course_Name>Computer Course</Course_Name>
<Course_Qual>O/L Pass</Course_Qual>
<Course_Dur>3 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>C#.net</Course_Conent_List>
<Course_Conent_List>VB.Net</Course_Conent_List>
<Course_Conent_List>Design Practices</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">5000</Fee_Amount>
<Fee_Comment></Fee_Comment>
</Course_Fee>
<Course_Desc>Basics</Course_Desc>
<Course_Next>Next October</Course_Next>
<Category_List>
<Cat_ID>1</Cat_ID>
</Category_List>
</Course_Details>
<Course_Details Course_ID="U002C0002">
<Course_Name>Accounting Course</Course_Name>
<Course_Qual>O/L Pass</Course_Qual>
<Course_Dur>6 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>Accounts Basics</Course_Conent_List>
<Course_Conent_List>Business Studies</Course_Conent_List>
<Course_Conent_List>Acc Pack</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">10000</Fee_Amount>
<Fee_Comment></Fee_Comment>
</Course_Fee>
<Course_Desc>Basic Accounting</Course_Desc>
<Course_Next>Next January</Course_Next>
<Category_List>
<Cat_ID>3</Cat_ID>
<Cat_ID>2</Cat_ID>
</Category_List>
</Course_Details>
</Course_Data>
</Uni_Details>
this is my XML file I need to retrieve all data which cat_id is 1
var data = (from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
where cats.Element("Course_Data").Element("Course_Details").Element("Category_List").Element("Cat_ID").Value == cat_id.ToString()
select new
{
uni_name = cats.Element("Uni_Name").Element("Full_Name").Value.ToString(),
uni_short = cats.Element("Uni_Name").Element("Short_Name").Value.ToString(),
price = cats.Element("Course_Data").Element("Course_Details").Element("Course_Fee").Element("Fee_Amount").Value.ToString()
});
however this works if I have cat_id 1 as my first element if its in second place it won't listed so plz help me with this
The problem is with the way the end of your where clause is setup: Element("Cat_ID").Value == cat_id.ToString().
Specifically, the Element("Cat_ID") part will check the first child "Cat_ID" element. So if Cat_ID 1 is the second item, it won't be found. Instead, you need to check all child elements for a match.
var data = (from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
let catId = cats.Element("Course_Data").Element("Course_Details").Element("Category_List").Elements("Cat_ID").FirstOrDefault(c => c.Value == cat_id.ToString())
where catId != null
select new
{
uni_name = cats.Element("Uni_Name").Element("Full_Name").Value.ToString(),
uni_short = cats.Element("Uni_Name").Element("Short_Name").Value.ToString(),
price = cats.Element("Course_Data").Element("Course_Details").Element("Course_Fee").Element("Fee_Amount").Value.ToString()
});
The query uses a let clause to store the result of the FirstOrDefault call, which uses the predicate to match the criteria. Next, if it isn't null then the rest of the query works as before. If it's null it means no match was found.
That said, your query has a lot of repeated elements. It also uses .Value.ToString() in a few places, which is redundant since the Value property already returns a string. I would clean up the query as follows:
var data = from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
let uniName = cats.Element("Uni_Name")
let details = cats.Element("Course_Data").Element("Course_Details")
let catId = details.Element("Category_List").Elements("Cat_ID").FirstOrDefault(c => c.Value == cat_id.ToString())
where catId != null
select new
{
uni_name = uniName.Element("Full_Name").Value,
uni_short = uniName.Element("Short_Name").Value,
price = details.Element("Course_Fee").Element("Fee_Amount").Value
};

LINQ Query for Filter Result

Experts,
I have a datatable with two columns:
1) One is Decimal
2) One is String
I write my filter query like:
var iFilterResult = from c in dataTable1.AsEnumerable()
where c.Field<string>("ACM_ACCOUNT_CODE").Contains(txtFindPrePaidExpenses.Text)
&& c.Field<string>("ACM_ACCOUNT_DESC").Contains(txtFindPrePaidExpenses.Text)
select new
{
ACM_ACCOUNT_CODE = c.Field<string>("ACM_ACCOUNT_CODE"),
ACM_ACCOUNT_DESC = c.Field<string>(" ACM_ACCOUNT_DESC")
};
gvSearchAccountGL.DataSource = iFilterResult;
gvSearchAccountGL.DataBind(); "
Here dataTable1 is Datatable Having Column
ACM_ACCOUNT_CODE of decimal type
ACM_ACCOUNT_DESC of string type.
use like Query for filter.
But it is not working
You're trying to use ACM_ACCOUNT_CODE as a string field - but you've said it's a decimal field.
It's not clear why you'd expect a decimal field to contain the same value as the description field. If you really want this, you could use:
c.Field<decimal>("ACM_ACCOUNT_CODE")
.ToString()
.Contains(txtFindPrePaidExpenses.Text)
... but I suspect you should rethink what the query is trying to do.

Convert DataTable to LINQ: Unable to query multiple fields

Importing a spreadsheet I have filled a DataTable object with that data and returns expected results.
Attempting to put this into a format I can easily query to search for problem records I have done the following
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select row["Order"].ToString();
}
Works as expected giving me a list of orders. However I cannot add other fields to this EnumerableRowCollection. Attempting to add other fields as follows gives me an error
public void Something(DataTable dt)
{
// row["Version"] throws an error on me
var data = from row in dt.AsEnumerable()
select row["Order"].ToString(), row["Version"].ToString();
}
Error: "A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row' which is already used in a 'child' scope to donate something else"
I'm thinking I need to alias the column name but I'm having no luck. What am I missing here?
It sounds like you're writing a bad select statement. Try the following:
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select new {
Order = row["Order"].ToString(),
Something = row["Something"].ToString(),
Customer = row["Customer"].ToString(),
Address = row["Address"].ToString()
};
}
That will create a new collection of Anonymously Typed objects that you can iterate over and use as needed. Keep in mind, though, that you want be able to return data from the function. If you need that functionality, you need to create a concrete type to use (in place of anonymous types).
I think you should use select new like this query for example:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
You probably want the following.
var data = from row
in dt.AsEnumerable()
select new { Order = row["Order"].ToString(), Version = row["Version"].ToString() };

Categories

Resources