I have this:
public class accounts
{
private string mName;
private string mEmail;
private string mAddress;
public accounts(string Name,
string Email,
string Address)
{
this.mName = Name;
this.mEmail = Email;
this.mAddress = Address;
}
}
then, somewhere else, I create this:
private static List<accounts> mlocalaccountList = new List<accounts>()
then I fill it like this:
mlocalaccountList.Add(new accounts("John Smith","johnsmith#mail.com","CA USA"));
Now, everything is OK, except, how can I access the list<> items??
You can access them in a foreach loop:
foreach (var item in mlocalaccountList) {
...
}
however, since all members are private you cannot access them at all. Consider making properties for the private members or making them public.
You can also access them by index:
mlocalaccountList[0]
is the first item in the list.
By indexer like an array
mlocalaccountList[0]
foreach (accounts a in mlocalaccountList) { /* do something */ }
will iterate through the list.
Try mlocalaccountList[0] or
foreach (accounts acct in mlocalaccountList)
{
// Do something with acct
}
I would recommend using a foreach statement or just access by using an index variable mlocalaccount[index]
You can iterate over them:
foreach (var item in mlocalaccountList)
{
// do stuff with item
}
You can use LINQ:
var usaItems = mlocalaccountList.Where(a => a.Address.Contains("USA"));
// assuming you implement a public property for Address
Here's a link to the List<T> MSDN page. The Members page lists all the methods and properties that you have available. You can find help on ForEach for example.
The MSDN library (http://msdn.microsoft.com/en-us/library/) is an invaluable source of information on the classes and their members.
Just combining the list of everyone's answers here so far:
Use an indexer into the list: mlocalaccountsList[i] will return the i'th element (0-based index, of course)
Iterate over the list using a loop. foreach(var account in mlocalaccountList) will easily provide you with each element in turn.
Use a LINQ query to filter out a specific element in the list. LINQ has two different styles of writing queries:
var result = mlocalaccountList.Where(a => a.Name == "John Smith"))
// or
var result = from a in mlocalaccountList
where a.Name == "John Smith"
select a;
Use a foreach statement:
foreach (accounts acc in mlocalaccountList)
{
... do something with acc
}
Though I don't program in C#, I believe it is: mlocalaccountList[index] where index is an int.
Related
I'm having some issues with my programm in c#.
Basically I have a list called mainList with 3 items in it. First two items are integers, but third one is another list containing more items.
mainList[0] = 8;
mainList[1] = 1;
mainList[2] = list;
By using foreach loop I'm able to print all of those items.
foreach (var i in (dynamic)(mainList[2]))
{
Console.WriteLine(i);
}
However I don't know how to access them. The thing is that I can't use indexes, because it is not an array. I would like to do something like this:
foreach (var i in (dynamic)(mainList[2]))
{
// First item is in datetime type, so I would like to change it to int
Console.WriteLine(Convert.ToInt64(i[1]));
}
Is there a way to access items inside list like we do it in arrays with a help of indexes?
Lists support the same index-based access as arrays, so you can use
mainList[n]
to access the nth entry in mainList.
I guess you are looking for something like this, although it is really unclear what you're asking:
foreach(var item in mainList)
{
if(item is System.Collections.IEnumerable)
{
foreach(var obj in ((System.Collections.IEnumerable)item))
{
Console.WriteLine(obj);
}
}
}
using the official mongo / c# drivers - what is the best way of returning an entire collection, and what is the best way of storing the data? I've seen some examples of iterating over a collection and returning a particular value, like this:
var collection = db.getCollection("users").findAll();
foreach (var value in collection){
value = collection["key"];
...
}
but what if I don't know the key names - and I just want to return the collection?
You dont need to know the key names when returning a collection.
public static void ReadCollectionDataUsingBson(string collectionName, string databaseName)
{
MongoDatabase database = CreateDatabase(databaseName);
MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName);
foreach (BsonDocument document in collection.FindAll())
{
foreach (string name in document.Names)
{
BsonElement element = document.GetElement(name);
Console.WriteLine("{0}: {1}", name, element.Value);
}
Console.WriteLine();
}
}
Note: CreateDatabase() function is user defined, so i have just shown you the required code over here.
I am fairly new to C#
I am trying to retrieve some information from an external data source and store it in array, once it is in an array I wish to sort it by time.
I know how to do this for just one column in a row, however the information I require has multiple columns.
For example:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
// Sort my array by Appoint.Start
foreach ( item in myNewArray )
{
//print out Appoint.Subject - Appoint.Start, Appoint.Organiser.Name.ToString() and Appoint.location
}
Many thanks for your help.
EDIT:
I have multiple data sources which pull in this:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
Hence the need to sort the items in a new array, I know this isn't very efficent but there is no way of getting the information I need in any other way.
You can sort a list using the LINQ sorting operators OrderBy and ThenBy, as shown below.
using System.Linq;
and then...
var appointments = new List<Appointment>();
var sortedAppointments = list.OrderBy(l => l.Subject).ThenBy(l => l.Name).ToList();
This will create a new list of appointments, sorted by subject and then by name.
It's unclear what your final aim is but:
Use a generic List instead of an array:
See this SO question for more information as to why using a List is prefered.
List<Appointment> appointments = new List<Appointment>();
foreach (Appointment Appoint in fapts)
{
appointments.Add(Appoint);
}
foreach (var item in appointments)
{
Console.WriteLine(item.Subject);
Console.WriteLine(item.Foo);
// Here you could override ToString() on Appointment to print eveything in one Console.WriteLine
}
If the aim of your code is to order by time, try the following:
var sortedAppointments = fapts.OrderBy(a => a.Start); // assuming Start is a DateTime property of `Appointment`.
Consider a Dictionary Object instead of an array if the data is conceptually one row multiple columns.
foreach(KeyValuePair<string, string> entry in MyDic)
{
// do something with entry.Value or entry.Key
}
You already have a list of objects in fpts, sort that list itself:
fpts.OrderBy(x => x.Subject).ThenBy(x => x.Location).ToList();
LINQ is your friend here.
fapts appears to already be a collection so you could just operate on it.
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start).ToArray()
I've used the ToArray() call to force immediate evaluation and means that myNewArray is already sorted so that if you use it more than once you don't have to re-evaluate the sort.
Alternatively if you are only using this once you can just as easily miss the ToArray() portion out and then execution of the sort will be deferred until you try and enumerate through myNewArray.
This solution puts the source objects into the array, but if you are just wanting to store the specific fields you mention then you will need to use a select. You have two choices for the array item type, you can either use an anonymous class which provides difficulties if you are returning this array from a function or define a class.
For anonymous:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
For named class assuming class is MyClass:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new MyClass {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
You have a wide range of options. The 2 most common are:
1) Create a class, then define an array or list of that class, and populate that
2) Create a structure that matches the data format and create an array or list of that
Of course, you could put the data into an XML format or dataset, but that's probably more work than you need.
public List<foo> appointments = new List<foo>();
public struct foo
{
public string subject ;
public DateTime start ;
public string name ;
public string location ;
}
public void foo1()
{
// parse the file
while (!File.eof())
{
// Read the next line...
var myRecord = new foo() ;
myRecord.subject = data.subject ;
myRecord.start = data.Start ;
myRecord.name = data.Name ;
//...
appointments.Add(myRecord);
}
}
Enjoy
(Since I can't comment and reply to the comment - it wasn't clear if he had a class, etc. or was just showing us what he wanted to do. I assumed it was just for demonstration purposes since there wasn't any info as to how the data was being read. If he could already put it into a class, than the first answer applied anyway. I just tossed the last 2 in there because they were options for getting the data first.)
I have a foreach statement that outputs a list of customer id's to a log file:
foreach(var customer in _response.CustomersList)
{
log.WriteLine(customer.CustID);
}
The Id's output correctly but the problem I have is I am not able to put them into one variable use them.
For example I wanted to give this request: _request2.CustID = customer.CustID but this is not correct.
I need those ID's because I have a cancel customer request:
public void Cancel()
{
_request2 = new CancelCust();
_request2.CommandUser = _request.CommandUser;
_request2.CustID = "This is where I would put the variable that holds the customer ID's"
_request2.Company = _request.Company;
}
So, how do I assign those id's to a variable to be used in my request later?
I'm not totally clear on what you are trying to accomplish with the code above. BUT, you could use a bit of LINQ and get a list of the IDs, then pass around that list as you like:
var customerIDs = _response.CustomersList.Select(customer => customer.CustID);
You can get all the customer Ids by storing them as you go:
var customerIds = new List<int>();
foreach (var customer in _response.CustomersList)
{
customerIds.Add(customer.CustId);
log.WriteLine(customer.CustID);
}
or by using LINQ
var customerIds = _response.CustomersList.Select(c => c.CustId);
As I pointed out in my comment, if the property Request.CustId is not a collection this won't help you request all of them at once. Are you able to change the definition of Request?
It sounds like your variable _request2.CustID is the wrong type. What error message are you getting from the compiler? (Or, is it a run-time error that you get?)
Something like this?
public void Cancel()
{
foreach(var customer in _response.CustomersList)
{
_request2 = new CancelCust();
_request2.CommandUser = _request.CommandUser;
_request2.CustID = customer.CustID;
_request2.Company = _request.Company;
}
}
With an ASP.NET MVC project I'm working on, I am required to check whether bit variables within a LINQ-To-SQL class are true. So far, After checking whether or not each variable is true or false, I then push the value of the field into a List and return it like so:
public List<String> GetVarList() {
List<String> list = new List<String>();
if (fields.SearchBar) {
list.Add("SearchBar");
}
if (fields.SomeField) {
list.Add("SomeField");
}
return list;
}
This, to me, doesn't seem to be the fastest or easiest way to do it.
I was wondering its possible to somehow be able check the value of the variable dynamically from an array of strings by looping through them with either a for or a foreach loop. For instance:
public List<String> GetVarList() {
String[] array = {"SearchBar", "SomeField"};
List<String> list = new List<String>();
foreach (String field in array) {
// Check whether or not the value is true dynamically through the array
}
return list;
}
Thanks for any suggestions!
Certainly, you can use reflection for something like this:
private bool ValueWasSet(string propertyName)
{
var property = fields.GetType().GetProperty(propertyName);
return (bool)property.GetValue(fields, null);
}
public List<string> GetVarList()
{
return new [] {"SearchBar", "SomeField"}
.Where(ValueWasSet)
.ToList();
}
It is a very straight-forward solution to what you want to do, assuming you have a lot of items to look through.
CAVEAT: This is NOT faster than your code. Your code is much faster than this... but if you want to do it more dynamically, you have to pay a slight perf price.
You can use reflection:
public List<String> GetVarList() {
String[] array = {"SearchBar", "SomeField"};
List<String> list = new List<String>();
var type=fields.GetType();
foreach (String field in array) {
var prop=type.GetProperty(field);
if ((bool)prop.GetValue(fields,null))
list.Add(field);
}
return list;
}
From your question is not clear if SearchBar, SomeFields etc. are fields or properties. If they are fields, change the code accordingly (use GetField() instead of GetProperty())