C# List of Items with multiple values [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Firstly please forgive me as I am still trying to get to grips with C# and OOP.
I am trying to build a simple console shopping basket as part of a challenge and I have a number of products which I need to be able to pull on to populate 5 different scenarios of the basket.
However I am unsure as to the best approach to listing each of the products which each have three different values (Desc, Dept, Price) and I wish to be able to select the items I need through a array, possibly.
Currently I have the items listed as such:
itemOnePrice = 10.50m;
itemTwoPrice = 54.65m;
itemThreePrice = 03.50m;
itemOneDept = "Clothing";
itemTwoDept = "Clothing";
itemThreeDept = "Head Gear";
itemOneDesc = "Hat";
itemTwoDesc = "Jumper";
itemThreeDesc = "Head Light";
I have looked at Lists and at Tuple, but I haven't been able to figure out how to really make these work for me. Can somebody please explain the best approach to list these products to pull from to populate my basket contents.

First, create a class
class Item
{
public decimal Price {get;set;}
public string Department {get;set;}
public string Description {get;set;}
}
Second, create the list
List<Item> items = new List<Item>();
items.Add(new Item{Price = 10.5m, Department = "Clothing", Description = "Hat"});
items.Add(new Item{Price = 54.65m, Department = "Clothing", Description = "Jumper"});
items.Add(new Item{Price = 03.50m, Department = "Head Gear", Description = "Head Light"});

Related

Which C# data structure should be used to store n number (e.g. 1million) of records [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a Person class and my design needs to have a capacity of up to a million persons. I need to be able to load in memory. I've tried various ways and they work ok for small sets but when the count gets anywhere close to a million it takes too much time and memory. Are there any C# data structures or strategies that are specialized for what I'm trying to do which is store N number (e.g. 1 million) of records for below Class?
Class Person
{
string Id {get;set;}
}
When you say store a million Person records my assumption is that you mean persistent storage and that you're not going to enter them by hand every time you run your app. One way to achieve this goal would be to use one of the various SQLite versions to store the records in a database format. When these records are retrieved with a query, the data can be used to populate a simple data structure like List<Person> or a more complex data structure like DataTable or ViewModel. To keep things simple, this example uses the sqlite-net-pcl NuGet package.
Here, the Person class has been modified with additional tags to let SQLite know how to configure the table:
[Table("Persons")]
class Person
{
[PrimaryKey]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() => $"{Id} {FirstName} {LastName}";
}
The first snippet creates a temporary database in memory and inserts three records to demo a few basics. To store it on disk, just change databasePath: ":memory:" to a writable path like {MyAppDataFolderPath}\{MyDatabaseName}.db.)
var database = new SQLiteConnection(databasePath: ":memory:");
database.CreateTable<Person>();
database.Insert(new Person { Id = "Admin.1", FirstName = "Tom", LastName = "Hanks" });
database.Insert(new Person { Id = "Admin.2", FirstName = "Tom", LastName = "Holland" });
database.Insert(new Person { Id = "Staff.1", FirstName = "Tom", LastName = "Cruise" });
Here are a few example of retrieving instances of Person from the database and putting them in a List<Person> data structure.
// How many Toms?
int count = database.ExecuteScalar<int>("SELECT COUNT(*) FROM Persons WHERE FirstName='Tom'");
Console.WriteLine($"Found {count} persons named 'Tom'");
// Match a pattern
Console.WriteLine("\nList Admin:");
List<Person> recordset =
database.Query<Person>(
"SELECT * FROM Persons WHERE Id LIKE 'Admin.%'");
foreach (Person record in recordset)
Console.WriteLine(record.ToString());
// Match multiple properties
Console.WriteLine("\nGet ID for Tom Cruise Person");
Person person =
database.Query<Person>(
"SELECT ID FROM Persons WHERE FirstName='Tom' AND LastName='Cruise'"
).First();
Console.WriteLine($"ID is {person.Id}");
As commented, your question could be answered in many different ways and this is just one approach, but it's one that I use in my own production code base which is shared between PC, iOS and Android versions.

Refactor code to make 3 size array dynamic in code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to refactor the code, I need to make this code dynamic, how to do that, see below part?
public class Trv34
{
public string CustomerNumber
public string ProductName
}
Models.Trv34[] itemTrv34 = new Models.Trv34[3]
itemTrv34[0] = new Models.Trv34 {CustomerNumber ="1", ProductName="p1"}
itemTrv34[1] = new Models.Trv34 {CustomerNumber ="2", ProductName="p2"}
itemTrv34[2] = new Models.Trv34 {CustomerNumber ="3", ProductName="p3"}
request.VODB.Trv34= new Models.Trv34[] {
itemTrv34[0],
itemTrv34[1],
itemTrv34[2],
};
I want to replace this part with something dynamic instead
itemTrv34[0],
itemTrv34[1],
itemTrv34[2],
The easiest way that comes to mind is to use Linq:
request.VODB.Trv34 = itemTrv34.ToArray();

how i can get the data that stored in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to generate a random number from first list (list of Object) and put it in the second list to get a random connection id to make connection between the original id and the random id how I can get the item from the first list by index and of which type I have to cast it
public class OneHub :Hub
{
static List<UserId> ConnectedUser = new List<UserId>();
static List<MessageDetail> CurrentMessage = new List<MessageDetail>();
static List<ConnectionsId> Connection = new List<ConnectionsId>();
public void Connect(string id)
{
if (ConnectedUser.Count(x => x.ConnectionId == id) == 0)
{
ConnectedUser.Add(new UserId { ConnectionId = id });
if (ConnectedUser.Count != 0 || ConnectedUser.Count != 1)
{
Random r = new Random();
int x = r.Next(0,ConnectedUser.Count);
(object)ConnectedUser.item[x];
Connection.Add(new ConnectionsId {ConnectionId=id,ConnectionId2= })
}}}
First off, you're going to need to make sure that the ConnectedUser that you randomly get is not the same user you are linking to, before you add that connection, or you're going to find further issues.
For ConnectedUser, you can get the index by simply using ConnectedUser[x]. (I suggest making your lists plural so it's obvious that they're collections.)
You need to assign that connected user to a new object.
Something like
UserID linkedUser = ConnectedUser[x];
This way, you can reference linkedUser.ConnectionId in your connection addition.
Alternately, you could just use:
Connection.Add(new ConnectionsId { ConnectionId = id, ConnectionId2 = ConnectedUser[x].ConnectionId };
This random setup, though, does have a strong potential for having several people ending up not linked to anyone. Additionally, your line that states:
if (ConnectedUser.Count != 0 ...
is redundant. You just added a user to that list. It should never be of size 0.

using for loops in C# for iterating through the master data [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I wanted to suggestion on the best practices in coding for a real scenario.
The scenario is this:
I have a list of 100 items.
public CustomObject
{
public int id {get;set;}
public string name {get;set;}
}
List<CustomObject> lstObj = new List<CustomObject>();
lstobj can have sample values such as
A,1 B,2 C,3 C,4 C,5 etc
Now, I have a tabular data as follows:
Low High
A 10 100
Z 89 100
while looping through the list, I need to check against this data, and if suppose A value is more than 100 I need to put it to some xml file.
Now, my approach is
a) I will be putting this master data into a list formatfor eg:
public class CheckValues
{
public string name { get;set;}
public int lowerlimit { get;set;}
public int upperlimit {get;set;}
}
and populating the list with the data like
Low High
A 10 100
Z 89 100
b) using a foreach loop , I will be looping the lstobj items and within this each iteration , I would be once again iterating the list to check if the item exists and if it exists whats the value (max or min)
Basically I am using the two forloops. Is it approach acceptable or is there any best practices/suggestions to improve the practice advisable on this?
If the number of entries in each list is small, your solution may be an acceptable solution, but if either of them is large, this is one of the worst ways to do it. A list means linear lookup (n*m). If you use some other container or if you sort first, you can achieve far better (n*1) performance.
I would recommend removing name:
public class CheckValues
{
public int lowerlimit {get;set;}
public int upperlimit {get;set;}
}
Then use Dictionary<string, CheckValues> to look up the limits
Dictionary<string, CheckValues> limits /* = ... */;
foreach(var item in data) // Just one foreach
{
var limit = limits[item]; // Looking up the limit is O(1) instead of O(n)
}
or you can use LINQ
List<CustomObject> lstObj = new List<CustomObject>(){ new CustomObject(){ id = 1, name = "name1" }, new CustomObject() { id = 2, name = "name2" } };
then you can select the highest value
CustomObject highestvalue = lstObj.OrderByDescending(x => x.id).FirstOrDefault();
or the lowest value
CustomObject lowestvalue = lstObj.OrderBy(x => x.id).FirstOrDefault();
you can also find data ids that's greater than 100
var objgreaterthan100 = lstObj.FindAll(x => x.id > 100);
then you can iterate to your objgreaterthan100 then put in XML.
foreach (var CustomObject in objgreaterthan100)
{
//your code for saving in xml
}

C# initialize object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The first 3 lines of code works fine..
How can I do the same when using object initializer ?
// works
Customer MyCustomerx = new Customer();
MyCustomerx.Location[0].place = "New York";
MyCustomerx.Location[1].place = "France";
// problem here
List<Customer> MyCustomer = new List<Customer>
{
new Customer() { Name= "Me",Location[0].place = "New York" }
}
There's no equivalent of that code within object initializers - you can't specify indexers like that. It's slightly unusual that it works even directly... I'd expect to have to add to a Locations property, rather than there being two already available which I could set an unconventionally-named property on. For example, this would be idiomatic:
Customer customer = new Customer {
Name = "Me",
Locations = {
new Location("New York"),
new Location("France")
}
};
(I'd probably put the name into a constructor parameter, mind you.)
You could then use that within a collection initializer, of course.

Categories