I've have this piece of code in C# which convert from one array to another:
IWebElement[] elements = Self.FindChildren()
Step[] steps = new Step[elements.Length];
for (int i = 0; i < elements.Length; i++)
{
steps[i] = new Step(elements[i]);
}
How can I write it in a shorter way (using linq or lambda expression) ?
Thanks
Omer
Linq approach
IWebElement[] elements = Self.FindChildren();
Step[] steps = elements.Select(x => new Step(x)).ToArray();
faster but without Linq
IWebElement[] elements = Self.FindChildren()
Step[] steps = new Step[elements.Length];
Array.Copy(elements, steps, elements.Length);
Related
Is there a more minimal way to write the following:
var voucherCodes = new List<string>();
for (int i = 0; i < 10; i++)
{
voucherCodes.Add(GenerateCode(VoucherCodeLength));
}
I would like to do something like this:
// ten items would be added to the list so long as GenerateCode returns a string
var voucherCodes = new List<string>(GenerateCode(VoucherCodeLength), 10);
Granted, I could create my own function, but I was wondering if there was something that already exists.
I can't say if it's better, but you can use the folloing LINQ "one-liner":
var voucherCodes = Enumerable.Range(0, 10).Select(_ => GenerateCode(VoucherCodeLength)).ToList();
or specifically for this call, and if the VoucherCodeLength is constant (or does not change and has no side effects), an even shorter:
var voucherCodes = Enumerable.Repeat(VoucherCodeLength, 10).Select(GenerateCode).ToList();
Another linqy way
var voucherCodes = Enumerable.Repeat(GenerateCode(VoucherCodeLength), 10).ToList();
Is there a way of creating a table with each cell containing a string in C# ?
The closest thing I found is multidimensional arrays string[,] names;, but it seems like its length needs to be defined which is a problem to me.
Here is what my code looks like :
string[] namePost;
int[] numbPage;
string post="";
string newPost;
int i=0;
int j=0;
foreach (var line in File.ReadLines(path).Where(line => regex1.Match(line).Success))
{
newPost = regex1.Match(line).Groups[1].Value;
if (String.Compare(newPost, post) == 0)
{
j = j + 1;
}
else
{
namePost[i] = post;
numbPage[i] = j;
post = newPost;
j = 1;
i = i + 1;
}
}
Each instance of the for writes the name of the new "post" in a cell of namePost. In the end, the namePost table stores the name of all the posts that are different from one another.
What is the best way to achieve that ?
If you are simply trying to store the posts, you can use the List class from the System.Collections.Generic namespace:
using System.Collections.Generic;
List<String> namePost = new List<String>();
Then, instead of namePost[i] = post;, use
namePost.Add(post);
DataTable
https://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
Use this, no need to define length at all.
Useful guide and examples:
http://www.dotnetperls.com/datatable
You can just use a
var table = new List<List<string>>();
This would give you a dynamic 2D table of strings.
This will give you all your unique posts. If you want the result as a list you can just do a
.ToList ()
with the result.
static IEnumerable<string> AllPosts(Regex regex, string filePath)
{
return File.ReadLines (filePath)
.Where (line => regex.Match (line).Success)
.Select (line => regex.Match (line).Groups [1].Value)
.Distinct ();
}
Below is my code which gives an error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'string[]'
I tried several times to solve the error. But I failed to do so.
if any body can suggest what could be the solution.. Thanks :)
public GetContentResponse GetContent(abcServiceClient client, QueryPresentationElementIDsResponse querypresentationelementresponse)
{
GetContentRequest GetContentRequest = new GetContentRequest();
GetContentResponse contentresponse = new GetContentResponse();
querypresentationelementresponse = presentationElementId(client);
List<string[]> chunks = new List<string[]>();
for (int i = 0; i < querypresentationelementresponse.IDs.Length; i += 25)
{
chunks.Add(querypresentationelementresponse.IDs.Skip(i).Take(25).ToArray());
contentresponse = client.GetContent(new GetContentRequest()
{
IDs = chunks // here i get this error
});
}
return contentresponse;
}
You're trying to assign a List to a string array. Convert the list to an array.
Since you haven't specified exactly where the error was I suppose it's when you're assign the IDs variable.
The following code would solve it:
public GetContentResponse GetContent(abcServiceClient client, QueryPresentationElementIDsResponse querypresentationelementresponse)
{
GetContentRequest GetContentRequest = new GetContentRequest();
GetContentResponse contentresponse = new GetContentResponse();
querypresentationelementresponse = presentationElementId(client);
List<string> chunks = new List<string>();
for (int i = 0; i < querypresentationelementresponse.IDs.Length; i += 25)
{
chunks.AddRange(querypresentationelementresponse.IDs.Skip(i).Take(25));
contentresponse = client.GetContent(new GetContentRequest()
{
IDs = chunks.ToArray()
});
}
return contentresponse;
}
I'm not sure what type IDs is or what line is giving you that error, but if I had to guess, I think its IDs = chunks.
It sounds like you are trying to convert a list to a string array. You need to use a method to convert using toArray().
Edit: Ok, you have an array of string arrays. You need to grab the correct one with:
IDs = Chunks.ToArray()[index]
Where index is the correct array. Not terribly familiar with the libraries you are working with, so I unfortunately cannot elaborate. However, to take a wild guess, try using i in place of index.
So, recently I've been looking into the HTML5 Indexeddb feature which is controlled with Javascript, and how to incorporate this with an SQL Server database to share and copy information across so that a version of the database is available offline.
The conundrum that I have is finding the best way to pass a set of objects from an SQL Server database through to the javascript of a browser, using C# to get the values from the database.
Though there are many little "hacks" that can be done (e.g Putting data into labels and then having the Javascript just pick it up document.getElementById("DataHere").value;) I was wondering if there were more efficient ways of passing the contents of a database across?
At the moment I have a method that generates an array of strings (all in the JSON format, using the JSON.Net package) as an example of what would be returned from the database.
public string[] GenerateEmployeeSample() {
List<Employee> listEmps = new List<Employee>();
string[] listJSON = new string[64];
string[] FirstNames = {"Alonso", "Alfred", "Angus", "Alfresco" };
string[] LastNames = {"Johnson","Williams", "Zelwegger", "Jones" };
string[] Departments = {"Finance", "Cleaning", "Pusher", "Stairs" };
string emailEnd = "#email.com";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
Employee tempEmp = new Employee();
tempEmp.FirstName = FirstNames[i];
tempEmp.LastName = LastNames[j];
tempEmp.Department = Departments[k];
tempEmp.Email = FirstNames[i] + "." + LastNames[j] + emailEnd;
listEmps.Add(tempEmp);
}
}
}
int count = 0;
foreach(Employee emp in listEmps){
string tempString = JsonConvert.SerializeObject(emp);
listJSON[count] = tempString;
count++;
}
return listJSON;
}
So now I have a set of data, how would I be able to pass this array through to Javascript?
I apologise if this is a trivial question but Javascript is still rather new to me, and after reading through quite a few examples that either didn't do what I wanted or just outright didn't work I am at a bit of a loss.
Thanks very much for reading!
To be more specific, you would make a resource (be it an aspx page or or a json file etc) that returns a JSON string when requested. You're already partway there with this step, because you've already got the code for serializing objects as JSON. A simple way of doing this would be to have a page that outputs the return value of this function using Response.Write(GenerateEmployeeSample());
Then you would use the XMLHttpRequest object to request this resource, and parse the returned JSON using javascript's JSON.parse, which returns a native javascript object. You may then do with this object as you please.
I have an ArrayList that import records from a database.
Is there any method to check whether the arrayList contains schname that i want to match to another list which is an api?
List<PrimaryClass> primaryList = new List<PrimaryClass>(e.Result);
PrimaryClass sc = new PrimaryClass();
foreach (string item in str)
{
for (int a = 0; a <= e.Result.Count - 1; a++)
{
string schname = e.Result.ElementAt(a).PrimarySchool;
string tophonour = e.Result.ElementAt(a).TopHonour;
string cca = e.Result.ElementAt(a).Cca;
string topstudent = e.Result.ElementAt(a).TopStudent;
string topaggregate = e.Result.ElementAt(a).TopAggregate;
string topimage = e.Result.ElementAt(a).TopImage;
if (item.Contains(schname))
{
}
}
}
This is what I have come up with so far, kindly correct any errors that I might have committed. Thanks.
How about ArrayList.Contains?
Try this
foreach( string row in arrayList){
if(row.contains(searchString)){
//put your code here.
}
}
Okay, now you've shown that it's actually a List<T>, it should be easy with LINQ:
if (primaryList.Any(x => item.Contains(x.PrimarySchool))
Note that you should really consider using foreach instead of a for loop to iterate over a list, unless you definitely need the index... and if you're dealing with a list, using the indexer is simpler than calling ElementAt.
// check all types
var containsAnyMatch = arrayList.Cast<object>().Any(arg => arg.ToString() == searchText);
// check strings only
var containsStringMatch = arrayList.OfType<string>().Any(arg => arg == searchText);