Set all values to one variable in c# - c#

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;
}
}

Related

How to put a value from array to another list in c#

Can anyone help me, guys?
this foreach is always error Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
even though I have given index 0, what's the solution
var store = _cartCollection.Find(x => x.id_cart == entity.id_cart).ToList();
int index = -1;
foreach (var cart in store)
{
var b = index++; // it shows
entity.cart[0].nama_produk = cart.nama_produk;
entity.cart[0].jumlah = cart.jumlah;
entity.cart[0].harga = cart.harga;
entity.cart[0].subtotal = cart.subtotal;
entity.cart[0].notes = cart.notes;
}
here is the class object
enter image description here
I think I declared the entity cart array / list incorrectly, do you know the correct method?
please dont be mean im a newbie
I am not sure what your exact issue is here, but I see a few "code smells" that might be causing the issue:
In this code block:
var store = _cartCollection.Find(x => x.id_cart == entity.id_cart).ToList();
int index = -1;
foreach (var cart in store)
It seems that you are retrieving a single cart based on its ID and then doing something with it. If I have that right, you can accomplish this much more simply with something like this:
var cart = _cartCollection.Find(x => x.id_cart == entity.id_cart).FirstOrDefault();
Then you don't need the for loop at all... just use the one cart you found.
On that note, you should also probably check cart for null... in case it doesn't exist... but that is up to your specific use case.
index is being incremented for each step in the loop... but its value is never used. Unless you have a reason to use it, I recommend just deleting it entirely... unless you intended to retrieve multiple carts and add them all to the entity.cart collection.
In this code block (which is what is actually throwing the error:
entity.cart[0].nama_produk = cart.nama_produk;
entity.cart[0].jumlah = cart.jumlah;
entity.cart[0].harga = cart.harga;
entity.cart[0].subtotal = cart.subtotal;
entity.cart[0].notes = cart.notes;
The code is not clear. My best guess at what you are trying to do is to add the details of the cart you found to a collection of cart information on the entity object. I also assume that entity.cart is a List or something like that.
If my assumptions are correct, then the reason you are getting the reason you are getting that exception is the cart[0] doesn't exist until you add a cart object to that list (which is probably what you are trying to do here. A more readable (and less error prone) way to do this would be:
var entityCart = new Cart {
nama_produk = cart.nama_produk,
jumlah = cart.jumlah,
harga = cart.harga,
subtotal = cart.subtotal,
notes = cart.notes
};
entity.cart.Add(entityCart);
It could be that you are trying to add products to a cart... in that case, you should change your variable names a bit, but the rest is very similar.

Arrays/Array Lists

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.)

How to check for list in LINQ

I am trying to read a file and process using LINQ.
I have a exclude list where if i encounter certain words in the file, i should omit that line
my code is
string sCodeFile = #"C:\temp\allcode.lst";
List<string> sIgnoreList = new List<string>() { "foo.c", "foo1.c" };
var wordsPerLine = from line in File.ReadAllLines(sCodeFile)
let items = line.Split('\n')
where !line.Contains(sIgnoreList.ToString())
select line;
foreach (var item in wordsPerLine)
{
console.WriteLine(item);
}
My LST file looks like below
\voodoo\foo.c
\voodoo\voodoo.h
\voodoo\std.c
\voodoo\foo1.h
in the end i want only
\voodoo\voodoo.h
\voodoo\std.c
How can i process the ignored list in contains? with my above code i dont get the desired output for sure
can any one help?
regards,
Karthik
Revised my answer. The bug is that you're doing a ToString on the ignore list, which certainly will not work. You must check each item in the list, which can be done using something like this:
where !sIgnoreList.Any(ignore => line.Contains(ignore))
A curiosity: since the above lambda is just passing a value into a method that only take the value as a parameter, you can write this even more compact as a method group like this:
where !sIgnoreList.Any(line.Contains)
Try this.
string sCodeFile = #"C:\temp\allcode.lst";
List<string> sIgnoreList = new List<string>() { "foo.c", "foo1.c" };
var wordsPerLine = File.ReadAllLines(sCodeFile).Where(n =>
{
foreach (var ign in sIgnoreList)
{
if (n.IndexOf(ign) != -1)
return false;
}
return true;
});
It passes the current element (n) to a lambda function, which checks it against every element of the sIgnoreList. Returning false means the element is ignored, true means it's returned.
Change it to:
where !sIgnoreList.Contains(line)
You need to compare each single line and check that it doesn't exist in the ignore list.
That's why the Vladislav's answer did not work.
Here's the working solution:
var result = from line in File.ReadAllLines(codeFile)
where !ignoreList.Any(line.Contains)
select line;
The problem was you didn't want to check for the whole path and messed up words/lines part a bit.

Create a list of items within 'var response'

I have the following code:
var request = new GeocodingRequest();
request.Address = postcode;
request.Sensor = "false";
var response = GeocodingService.GetResponse(request);
var result = response.Results. ...?
I'd very much like to get result as a list, but I can't seem to convert it. I know I can do something like response.Results.ToList<string>();, but have had no luck.
Can anyone help please :)
Well you can just use:
GeocodingResult[] results = response.Results;
or
List<GeocodingResult> results = response.Results.ToList();
If you want a list of strings, you'll need to decide how you want to convert each result into a string. For example, you might use:
List<string> results = response.Results
.Select(result => result.FormattedAddress)
.ToList();
It is defined as:
[JsonProperty("results")]
public GeocodingResult[] Results { get; set; }
if you want to make it list call: response.Results.ToList().
But why do you want to make it list? You can insert items into list, but I don't think you need it.
assuming response.Results is IEnumerable, just make sure System.Linq is available as a namespace and say response.Results.ToList()

Stuck with List<>

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.

Categories