Is there any way to insert part of the code between { } dynamically?
LINQ QUERY:
var csvdata = from csvline in csvlines
let column = csvline.Split(';')
select new {
produkt = column[0],
cislo = column[1],
part = column[2],
serial = column[3]
};
I mean something like:
string qpart = "produkt = column[0], cislo = column[1], part = column[2], serial = column[3]";
var csvdata = from csvline in csvlines
let column = csvline.Split(';')
select new {
qpart
};
Thanks for answers..
Try investigating Dynamic Linq Query Library.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
http://naspinski.net/post/Writing-Dynamic-Linq-Queries-in-Linq-to-Entities.aspx
You'll need to convert the string array returned from Split into IQueryable for it to work but I think this is your best shot.
var results = columns
.Select("new(column[0] As produkt)");
Is how I'd I imagine it would work?.
Related
i have 'created date' and 'closed date' in my file and i'm converting it in json so i have that dates in json.
in my method i have two parameter like from date and to date and i want to count particular column data of my file between from date and to date.so how can we write code to fetch it using linq.
i tried this...
public JsonResult StatusDerails(DateTime from,DateTime to)
{
string csvurl = WebConfigurationManager.AppSettings["csvfileurl"];
var lines = System.IO.File.ReadAllLines(csvurl).Skip(1);
List<Product> prdt = new List<Product>();
foreach (string line in lines)
{
Product c1 = new Product();
var split = line.Split(',');
c1.ID = Int32.Parse(split[0]);
c1.Area_Path = split[1];
c1.IterationPath = split[2];
c1.State = split[3];
c1.Reason = split[4];
c1.Priority = Int32.Parse(split[5]);
c1.Severity = split[6];
c1.Tags = split[7];
c1.Title = split[8];
c1.CreatedDate = split[9];
c1.CreatedBy = split[10];
c1.ResolvedDate = split[11];
c1.ResolvedBy = split[12];
c1.ClosedDate = split[13];
c1.AssignedTo = split[14];
prdt.Add(c1);
}
//var list = prdt.GroupBy(a=>a.AreaPath).Select(a=>new UIproduct() {
var productName = prdt.Select(a => a.Area_Path).Distinct();
List<StatusDetail> statusdetail = new List<StatusDetail>();
foreach (var Name in productName)
{
StatusDetail sd = new StatusDetail();
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date.ToString() && a.ClosedDate <= to.Date.ToShortDateString
}
return Json(statusdetail, JsonRequestBehavior.AllowGet);
}
The comparison of DateTime as string will not be a good option and that wont gives you the exact result, So I recommend you to change the type of CreatedDate and ClosedDate to DateTime. and compare two DateTime values in linq. I think instead of splitting json for creating object of certain types you can use json converters.
Fix for your scenario:
c1.CreatedDate = DateTime.Parse(split[9]);
c1.ClosedDate = DateTime.Parse(split[13]);
Don't forget to change the type in the class, Now its fine to use the linq as like the following:
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date && a.ClosedDate <= to.Date);
I have a query somewhat like the following which I'm trying to parameterize:
List<string> poiIDs = /*List of poi ids*/;
List<string> parameterNames = /*List of parameter names*/;
string inClause = string.Join(",", parameterNames);
string query = string.Format("SELECT c.id AS poiID, c.poiName, c.latitude, c.longitude FROM c WHERE c.clusterName = #clusterName AND c.id IN ({0}) AND c.deleted = false", inClause);
IQueryable<POI> queryResult = Client.CreateDocumentQuery<POI>(Collection.SelfLink, new SqlQuerySpec
{
QueryText = query,
Parameters = new SqlParameterCollection()
{
new SqlParameter("#clusterName", "POI"),
// How do I declare the dynamically generated parameters here
// as new SqlParameter()?
}
});
How do I declare the dynamically generated parameters as new SqlParameter() for the Parameters property of SqlQuerySpec in order to create my document query?
You can create dynamic parameterized query like this:
// DocumentDB query
// POINT TO PONDER: create the formatted query, so that after creating the dynamic query we'll replace it with dynamically created "SQL Parameter/s"
var queryText = #"SELECT
us.id,
us.email,
us.status,
us.role
FROM user us
WHERE us.status = #userStatus AND us.email IN ({0})";
// contain's list of emails
IList<string> emailIds = new List<string>();
emailIds.Add("a#gmail.com");
emailIds.Add("b#gmail.com");
#region Prepare the query
// simple parameter: e.g. check the user status
var userStatus = "active";
var sqlParameterCollection = new SqlParameterCollection { new SqlParameter("#userStatus", userStatus) };
// IN clause: with list of parameters:
// first: use a list (or array) of string, to keep the names of parameter
// second: loop through the list of input parameters ()
var namedParameters = new List<string>();
var loopIndex = 0;
foreach (var email in emailIds)
{
var paramName = "#namedParam_" + loopIndex;
namedParameters.Add(paramName);
var newSqlParamter = new SqlParameter(paramName, email);
sqlParameterCollection.Add(newSqlParamter);
loopIndex++;
}
// now format the query, pass the list of parameter into that
if (namedParameters.Count > 0)
queryText = string.Format(queryText, string.Join(" , ", namedParameters));
// after this step your query is something like this
// SELECT
// us.id,
// us.email,
// us.status,
// us.role
// FROM user us
// WHERE us.status = #userStatus AND us.email IN (#namedParam_0, #namedParam_1, #namedParam_2)
#endregion //Prepare the query
// now inject the parameter collection object & query
var users = Client.CreateDocumentQuery<Users>(CollectionUri, new SqlQuerySpec
{
QueryText = queryText,
Parameters = sqlParameterCollection
}).ToList();
The following gives you a SQL query, you can then run in your DocumentDB Collection, to get the Documents by their IDs.
var query = $"SELECT * FROM p WHERE p.id IN ('{string.Join("', '", arrayOfIds)}')";
The DocumentDB SDK doesn't support parameterized IN queries.
Judging from the SO thread in the comment above, SQL does not either. As mentioned in the other thread, you can use LINQ as a workaround.
Why not use the ArrayContains method? Here is an example in node
sqlQuery = {
query: 'SELECT * FROM t WHERE ARRAY_CONTAINS(#idList, t.id)',
parameters: [
{
name: '#idList',
value: ['id1','id2','id3'],
},
],
};
How do I edit the data in each Address Line, since they all have the same name?
<StructuredAddress>
<AddressLine></AddressLine>
<AddressLine></AddressLine>
<AddressLine></AddressLine>
</StructuredAddress>
My code so far, which doesn't work, is this. How do I isolate each AddressLine indivisually and insert the appropriate data?
XElement StructuredAddress = PatientAddress.Descendants("StructuredAddress").First();
StructuredAddress.Element("AddresLine").Value = cc.address1;
StructuredAddress.Element("AddresLine").Value = cc.address2;
StructuredAddress.Element("AddresLine").Value = cc.address3;
You may want to access each <AddressLine> using it's index :
XElement StructuredAddress = PatientAddress.Descendants("StructuredAddress").First();
var address = StructuredAddress.Elements("AddresLine").ToList();
address[0].Value = cc.address1;
address[1].Value = cc.address2;
address[2].Value = cc.address3;
You could iterate them which will present them in ordinal order:
foreach (var addressLine in StructuredAddress.Elements("AddressLine"))
{
addressLine.Value = ...
}
Or by index;
var lines = StructuredAddress.Elements("AddressLine").ToList();
lines[0].Value = "...";
Is it possible to apply a Linq query from a HttpPostedFileWrapper?
My web app allows users to select a bunch of .csv files. I now need to open those files and import them.
My previous code, which uses paths and file names looks like;
importedList = (from csvLine in File.ReadAllLines(fileName)
let x = csvLine.Split(',')
select new ImportedXDock
{
StoreNumber = int.Parse(x[0]),
DCNumber = int.Parse(x[1]),
DeliveryDay = x[2],
Activity = x[3],
ActivityDay = x[4],
Time = TimeSpan.Parse(x[5])
}).ToList();
However, now that i have a collection of HttpPostedFileWrapper objects how would I do the same?
edit
Or do I need to convert it to something and then read the file?
You may be able to loop over the file names instead of the input streams
foreach (var fileName in wrapper.Select(w => w.FileName))
{
yield return (from csvLine in File.ReadAllLines(fileName)
let x = csvLine.Split(',')
select new ImportedXDock
{
StoreNumber = int.Parse(x[0]),
DCNumber = int.Parse(x[1]),
DeliveryDay = x[2],
Activity = x[3],
ActivityDay = x[4],
Time = TimeSpan.Parse(x[5])
}).ToList();
}
I am using a stream reader to read a text file and then using Linq for retrieving the information
String fileContent = prodFileStreamReader.ReadToEnd();
var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
where !String.IsNullOrEmpty(con)
select new BaseSegment
{
dataID = con.Substring(0, con.IndexOf('#')),
dataElms = con.Split('#').ToArray(),
dataCon = con,
lineNumber =
};
I would also like to get the line number. I tried using Index but I was not able to. How to query to get the index and assign it to lineNumber?
Try using the select that projects index into each item, as given in this msdn article: http://msdn.microsoft.com/en-us/library/bb534869.aspx
In your case something like this (not tested):
var mydata = fileContent.Split('$')
.Select(x => x.Trim())
.Where(con => !String.IsNullOrEmpty(con))
.Select((con, index) => new
{
dataID = con.Substring(0, con.IndexOf('#')),
dataElms = con.Split('#').ToArray(),
dataCon = con,
lineNumber = index
});
For starters, I would not read the file in as a big string. Use methods that could process it in small chunks. Use File.ReadLines() for example to read through the file line by line. It will be easier to get line numbers this way and much more efficient than reading it all at once only to split it up again.
const string filePath = ...;
var myData =
from pair in File.ReadLines(filePath)
.Select((LineNumber, Line) => new { LineNumber, Line })
where ...
select new BaseSegment
{
...
Line = pair.Line,
LineNumber = pair.LineNumber,
};
p.s., You should stick to the usual C# naming conventions. Public properties of your classes should use PascalCasing, not camelCasing and should not be abbreviated.
The code you use to process the content looks awkward. It could probably be improved if I knew what the files looked like. I'll leave that out until you could show us how it is.
How about this?
var animalList = from a in animals
select new { Animal = a, Index = animals.IndexOf(a) };
or in your case...
Index = fileContent.IndexOf(con)
if this whole data is going in myData then you can use the index directly from the myData.
Try This:
String fileContent = prodFileStreamReader.ReadToEnd();
var mydata = from con in fileContent.Split('$').Select(x => x.Trim())
where !String.IsNullOrEmpty(con)
select new BaseSegment
{
dataID = con.Substring(0, con.IndexOf('#')),
dataElms = con.Split('#').ToArray(),
dataCon = con,
lineNumber = Array.IndexOf(fileContent.Split('$').Select(x => x.Trim(),con)
};
Array.IndexOf(yourArrey,the string you looking for); -> will return the index in the arrey.
you can try something like this
long index = 0;
var xElementsAndNodes = from xmlElement in elementsColl
select new
{
Index = index += 1,
....
}