I am trying to create an array of 20 candidates from my Candidate class. So far, this is what I have:
Candidate candidate0 = new Candidate();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
...
Candidate candidate19 = new Candidate();
Candidate[] candidates = new Candidate[20];
candidates[0] = candidate0;
candidates[1] = candidate1;
candidates[2] = candidate2;
candidates[3] = candidate3;
...
candidates[19] = candidate19;
I know this is not the correct or 'best' way to do this. What would be the best way?
What you need is a for loop :
int candidateLength = 20 ;
Candidate[] candidates = new Candidate[candidateLength ];
for(int i=0 ; i<candidates.Length ; i++)
{
candidates[i] = new Candidate();
}
Adam - you'd be subjectively better off using a list for this along the lines of:
List<Candidate> canditateList = new List<Candidate>();
// MaxLength is a const defined somewhere earlier perhaps
for(int i=0 ;i<MaxLength;i++){
canditateList.Add(new Candidate(){... properties here});
}
// etc, etc.
You could then factor this out to an array if required using:
var candidateArray = canditateList.ToArray();
Just my initial thoughts, tho you may of course have a good reason for wishing to use an array from the start, my premise is that I would go with a list and party on that for various extracted flavours.
Related
I've tried add new encounter but it shows "System.NullReferenceException: 'Object reference not set to an instance of an object'". Heare is my code:
private static void AddEncounter()
{
var encount = new Encounter();
encount.Identifier.Add(new Identifier
{
Use = (Identifier.IdentifierUse?)1,
System = "http://www.amc.nl/zorgportal/identifiers/visits",
Value = "tek001"
}) ;
encount.Class = new Coding("http://terminology.hl7.org/CodeSystem/v3-ActCode", "SS", "Lưu trú ngắn hạn");
encount.Status = 0;
encount.Priority = new CodeableConcept("http://terminology.hl7.org/CodeSystem/v3-ActPriority", "R", "routine");
encount.Subject = new ResourceReference("Patient/a07b880381ec44ad8f80743f396c8011/_history/1", "Lâm");
encount.Length.Value = 120;
encount.Length.Unit = "min";
encount.Length.System = "http://unitsofmeasure.org";
encount.Length.Code = "min";
encount.ReasonCode.Add(new CodeableConcept("http://snomed.info/sct", "184004", "Rối loạn nhịp tim rút"));
encount.Hospitalization.PreAdmissionIdentifier.Use = (Identifier.IdentifierUse?)1;
encount.Hospitalization.PreAdmissionIdentifier.System = "http://www.amc.nl/zorgportal/identifiers/pre-admissions";
encount.Hospitalization.PreAdmissionIdentifier.Value = "1598753";
encount.Hospitalization.AdmitSource = new CodeableConcept("http://terminology.hl7.org/CodeSystem/admit-source", "outp", "Khoa ngoại trú");
encount.Hospitalization.DischargeDisposition = new CodeableConcept("http://terminology.hl7.org/CodeSystem/discharge-disposition", "hosp", "Bệnh nhân đã được xuất viện và chăm sóc giảm nhẹ");
Console.WriteLine("Successful");
Console.ReadLine();
}
How can i add an exactly?
Just like you do with creating the Identifier for the Identifier field and the other complex objects for the Class, Priority and Subject fields, you will need to create a Duration for the Length field:
encount.Length = new Duration();
encount.Length.Value = 120;
// etc.
You will have to do this for all of the complex objects you use in your code, so also for the Hospitalization field and the PreAdmissionIdentifier:
encount.Hospitalization = new Encounter.HospitalizationComponent();
encount.Hospitalization.PreAdmissionIdentifier = new Identifier();
// etc.
Another change I would like to advice, is to make use of the values provided in the enum for the identifier use, to make your code more readable and your intention clear:
encount.Hospitalization.PreAdmissionIdentifier.Use = Identifier.IdentifierUse.Official;
It's difficult to say for certain without seeing the entire class but System.NullReferenceException is thrown when trying to access something that has not been instantiated.
encount.Hospitalization is likely a reference to another class which must first be instantiated. Try first creating and instance before accessing (example below).
encount.Length = new Length();
encount.Hospitalization = new Hospitalization();
Note: I'm guessing the class names (Length and Hospitalization) so you may need to adjust for your code. The main idea is that you must create the class (new ...()) before utilizing\accessing.
I am facing a problem I can not solve. and I hope someone can.
// I got Table saved in M.SQL server as in Picture
// Code
DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => x );
I want to instantiate every string ( i.Position) as a new instant name of class ARTICLE.like the followings
foreach ( var i in ALL)
{
ARTICLE "i.Position" = new ARTICLE();
"i.Name".A_STOCK = i.Stock ;
}
// The Class
public Class ARTICLE
{
public int A_STOCK { get; set;}
}
// later I want to recall it to get its A_STOCK value , for example
int k1 = A1.A_STOCK ;
int k2 = A2.A_STOCK ;
//
In short , I want to retrieve all strings in Position Column and convert every string of them into a a new instant of class (ARTICLE) carries then instant name ...
Thank you very much ...
Pretty easy, just do it in your select using object initialization syntax.
DB_Context MYDB = new DB_Context();
var ALL = MYDB.select(x => { new ARTICLE { A_STOCK = x.Stock}; );
After making this change, ALL will contain a list of ARTICLE objects instead of a list of strings.
You can use a List<T>:
var articles = new List<ARTICLE>();
foreach(var i in ALL)
articles.Add(new ARTICLE() { A_STOCK = i.Stock });
var k1 = articles[0].A_STOCK;
var k2 = articles[1].A_STOCK;
///etc...
Btw, so many things wrong with your style.... Have a look at https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
I'm attempting to move from using VB WPF to C# WPF, What I have attempted so far is using an online converter because of the amount of code I have. The problem being that I have come into some troubles understanding some errors presented and being a beginner in C# I'm a little lost.
The code below is what I'm currently using with standard VB WPF and work perfectly fine and a copy of what the c# converter changes it into. (Note I have added Bing Maps WPF Reference to both VB and C#)
Private Sub Aberdeen() Handles BTNCounty.Click
If TXTCounty.Text = "Aberdeen" Then
Dim CountyLocation(2) As Microsoft.Maps.MapControl.WPF.Location
CountyLocation(0) = New Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584)
CountyLocation(1) = New Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584)
CountyLocation(2) = New Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633)
Dim names = New String() {"Aberdeen Central", "Aberdeen Lochnagar", "Aberdeen Kincorth"}
For index = 0 To CountyLocation.Length - 1
Dim Pin = New Microsoft.Maps.MapControl.WPF.Pushpin()
Dim CoordinateTip = New ToolTip()
CoordinateTip.Content = names(index)
Pin.Location = CountyLocation(index)
Pin.ToolTip = CoordinateTip
BingMap.Children.Add(Pin)
Next
End If
End Sub
Below is the example of the converted code into c#
private void Aberdeen()
{
if (TXTCounty.Text == "Aberdeen") {
Microsoft.Maps.MapControl.WPF.Location[] CountyLocation = new Microsoft.Maps.MapControl.WPF.Location[3];
CountyLocation(0) = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation(1) = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation(2) = new Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633);
dynamic names = new string[] {
"Aberdeen Central",
"Aberdeen Lochnagar",
"\tAberdeen Kincorth"
};
for (index = 0; index <= CountyLocation.Length - 1; index++) {
dynamic Pin = new Microsoft.Maps.MapControl.WPF.Pushpin();
dynamic CoordinateTip = new ToolTip();
CoordinateTip.Content = names(index);
Pin.Location = CountyLocation(index);
Pin.ToolTip = CoordinateTip;
BingMap.Children.Add(Pin);
}
}
}
I recieve 3 errors which I was wondering if you could tell me what they mean and how to resolve the issue?
CountyLocation is a variable but used like a method?
2 The name index does not exist in the current context?
3 System.Windows.FrameworkElement.ToolTip is a property but is used like a type?
Any help would be much appreciated as this very much foreign territory for me.
Please see the answers inline.
The main issue is that the converter has converted all your type inference calls (Dim variable = ...) to dynamics, which is incorrect. You should use var for type inference.
private void Aberdeen()
{
if (TXTCounty.Text == "Aberdeen") {
Microsoft.Maps.MapControl.WPF.Location[] CountyLocation = new Microsoft.Maps.MapControl.WPF.Location[3];
// Error 1: Setting array variables is done using square brackets, otherwise it's considered a method invocation
CountyLocation[0] = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation[1] = new Microsoft.Maps.MapControl.WPF.Location(57.143652, -2.1056584);
CountyLocation[2] = new Microsoft.Maps.MapControl.WPF.Location(57.124838, -2.0991633);
// extra: you don't need dynamic here, just var will do
var names = new string[] {
"Aberdeen Central",
"Aberdeen Lochnagar",
"\tAberdeen Kincorth"
};
// Error 2: you need to declare the index variable (added var)
for (var index = 0; index <= CountyLocation.Length - 1; index++) {
// Error 3: don't need dynamic here
var Pin = new Microsoft.Maps.MapControl.WPF.Pushpin();
// don't need dynamic here
var CoordinateTip = new ToolTip();
// Same as error 1: Array access is done with square brackets
CoordinateTip.Content = names[index];
// Same as error 1: Array access is done with square brackets
Pin.Location = CountyLocation[index];
Pin.ToolTip = CoordinateTip;
BingMap.Children.Add(Pin);
}
}
}
Is there an easy way, and most importantly, more optimized to do the fowling code:
class Chair{
int numberOfLegs=4;
}
class House{
Chair chair;
String name="My Home";
}
// add chairs to each house
IList<Chair> chairs = new List<Chair>(10); // let us imagine that we have 10 different chairs...
// Code to replace:
IList<House> houses = new List<House>(chairs.Count());
for (int i = 0; i < houses.Count(); i++){
houses[i].chair = chairs[i]
}
My own suggestion it is replacing the for with Linq
// Code to replace:
IList<Homes> homes = chairs.Select(c => new Home{ Chair = c}).ToList();
Is it faster than the old code?
Do you have a better idea? Maybe using chairs.AsParallel?
I have an issue here a bit complex than I'm trying to resolve since some days ago. I'm using the PetaPoco ORM and didn't found any other way to do a complex query like this:
var data = new List<string[]>();
var db = new Database(connectionString);
var memberCapabilities = db.Fetch<dynamic>(Sql.Builder
.Select(#"c.column_name
,CASE WHEN c.is_only_view = 1
THEN c.is_only_view
ELSE mc.is_only_view end as is_only_view")
.From("capabilities c")
.Append("JOIN members_capabilities mc ON c.capability_id = mc.capability_id")
.Where("mc.member_id = #0", memberID)
.Where("c.table_id = #0", tableID));
var roleCapabilities = db.Fetch<dynamic>(Sql.Builder
.Select(#"c.column_name
,CASE WHEN c.is_only_view = 1
THEN c.is_only_view
ELSE rc.is_only_view end as is_only_view")
.From("capabilities c")
.Append("JOIN roles_capabilities rc ON c.capability_id = rc.capability_id")
.Append("JOIN members_roles mr ON rc.role_id = mr.role_id")
.Where("mr.member_id = #0", memberID)
.Where("c.table_id = #0", tableID));
I'm trying to get the user capabilities, but my system have actually to ways to assign an user a capability, or direct to that user or attaching the user to a role. I wanted to get this merged list using a stored procedure but I needed cursors and I thought maybe should be easier and faster doing this on the web application. So I get that two dynamics and the members capabilities have priority to the roles capabilities, so I need to check if that using loops. And I did like this:
for (int i = 0; i < roleCapabilities.Count; i++)
{
bool added = false;
for (int j = 0; j < memberCapabilities.Count; j++)
if (roleCapabilities[i].column_name == memberCapabilities[j].column_name)
{
data.Add(new string[2] { memberCapabilities[j].column_name, Convert.ToString(memberCapabilities[j].is_only_view) });
added = true;
break;
}
if (!added)
data.Add(new string[2] { roleCapabilities[i].column_name, Convert.ToString(roleCapabilities[i].is_only_view) });
}
So now the plan is delete the duplicate entries. I have try using the following methods with no results:
data = data.Distinct();
Any help? Thanks
Make sure that your object either implements System.IEquatable or overrides Object.Equals and Object.GetHashCode. In this case, it looks like you're storing the data as string[2], which won't give you the desired behavior. Create a custom object to hold the data, and do one of the 2 options listed above.
If I understand your question correctly you want to get a distinct set of arrays of strings, so if the same array exists twice, you only want one of them? The following code will return arrays one and three while two is removed as it is the same as one.
var one = new[] {"One", "Two"};
var two = new[] {"One", "Two"};
var three = new[] {"One", "Three"};
List<string[]> list = new List<string[]>(){one, two, three};
var i = list.Select(l => new {Key = String.Join("|", l), Values = l})
.GroupBy(l => l.Key)
.Select(l => l.First().Values)
.ToArray();
You might have to use ToList() after Distinct():
List<string[]> distinct = data.Distinct().ToList();