How to alter multiple objects in list c# - c#

The user must enter the name of the student and then enter the number of faults he has (the numFaltas column)
How do I change only the numFalts column and keep the rest?
Sorry for English. I'm learning yet.
Thank you!
My list:
alunosMatriculados.Add(new Aluno
{
matAluno = 1,
nomeAluno = "THIAGO BUARQUE",
cpfAluno = "111.111.111-11",
turmaAluno = "3H",
numFaltas = 4
});
alunosMatriculados.Add(new Aluno
{
matAluno = 2,
nomeAluno = "MARIANA DA SILVA",
cpfAluno = "111.111.111-12",
turmaAluno = "2I",
numFaltas = 0
});

You can do something like this:
if (alunosMatriculados.Any(a => a.nomeAluno == inputName))
alunosMatriculados.Where(a => a.nomeAluno == inputName).ToList().ForEach(a =>a.numFaltas = inputFaults);
But be careful because if there's more than one student with the same name you will change the faults for all of them. It would be better to make sure that the names are unique or use an unique field like an ID (maybe your matAluno)

You can do this in simple way by using foreach loop
You first verify that If your inputName parameter is null or not
Like
if (!String.IsNullOrEmpty(inputName))
{
foreach (Aluno a in alunosMatriculados)
if (a.nomeAluno == inputName)
a.numFaltas = inputValue;
}
in above code can comapre id also instead of inputName in inner if condition
By this way can only alter your numFaltas and any other also that you want

Related

LINQ Expression - Returning a UserID based on the Name Specified in a LinkLabel

Please, I am trying to access my database to get access to a user id. But when i try accessing, what gets returned is 0. Initially, i had issues figuring out how to change this SQL statement (SELECT user_id FROM users WHERE firstname = 'Godymn') to LINQ. But i later found that i could use :
var result = users.Where(x=>x.firstname == "Godymn").Select(x=>x.userid);
So far, when i tried to use the query in my code, it returns a 0. But what i need is to return the user id based on the name specified in the linkLabel. I have not been able to figure out why its not working.
Will appreciate any help.
Here is my code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel())
{
result = db.users.Where(x => x.firstname == link).Select(x => x.user_id).FirstOrDefault();
}
return result;
}
Here is the button i used to check the content of what got returned.
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Good Afternoon Godymn.
Here are some possible scenarios:
1 - The user name Godymn does not exist in the database
2 - The user_id is 0.
Try checking this 2 scenarios.
After that, you could change your approach to a more "debug friendly" level.
var result = db.users.First(f => f.firstname == link);
Then, check if result is null. If it is null, the name was not found in the database.
If it is not null, check if the result is 0.
Why this approach: This way, you can tell if the problem is when you are searching for the user or when you are binding the value of Id.
I can't comment, i'm sory, but first of all i'll try this:
var foo = db.users.Select(x => x).ToList();
then you can investigate your result like this
i suppose you try get wrong data (or wrong structure)
when i stuck i do this:
Or maybe you can attach your structure of object?
So yeah, I was able to fix the bug. The problem was with the linkLabelPartner.Text as Chris Dunaway rightly said. As soon as he mentioned if the linklabel contains only firstname, I just knew that was the missing piece. This holds firstname and lastname and I only accounted for just firstname. Hence the value returned remains at 0. So, all I had to do was to concatenate both firstname and lastname which solved the issue. So, yeah the query I used initially was right.
Here is the code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel ())
{
result = db.users.Where(x => x.lastname + " " + x.firstname == link ).Select(x => x.users).FirstOrDefault();
}
return result;
}
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Many thanks everyone for your suggestions, appreciate.

Lambda SQL Query / Manipulate String At Query Or After Result

I'm using C#, EF5, and Lambda style queries against SQL.
I have the usual scenario of binding data to gridviews. Some of the results for my columns may be too long (character count) and so I only want to display the first 'n' characters. Let's say 10 characters for this example. When I truncate a result, I'd like to indicate this by appending "...". So, let's say the following last names are returned:
Mercer, Smith, Garcia-Jones
I'd like them to be returned like this:
Mercer, Smith, Garcia-Jon...
I was doing something like this:
using (var context = new iaiEntityConnection())
{
var query = context.applications.Where(c => c.id == applicationPrimaryKey);
var results = query.ToList();
foreach (var row in results)
{
if (row.employerName.Length > 10)
{
row.employerName = row.employerName.Substring(0, Math.Min(10, row.employerName.ToString().Length)) + "...";
}
if (row.jobTitle.Length > 10)
{
row.jobTitle = row.jobTitle.Substring(0, Math.Min(10, row.jobTitle.ToString().Length)) + "...";
}
}
gdvWorkHistory.DataSource = results;
gdvWorkHistory.DataBind();
However, if I change my query to select specific columns like this:
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
c.applicationCategoryLong,
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})
The result appears to become read-only if specific columns are selected, and I really should be selecting just the columns I need. I'm losing my ability to edit the result set.
So, I'm rethinking the entire approach. There must be away to select the first 'n' characters on select, right? Is there anyway to append the "..." if the length is > 10 on select? That seems trickier. Also, I guess I could parse through the gridview after bind and make this adjustment. Or, perhaps there is a way to maintain my ability to edit the result set when selecting specific columns?
I welcome your thoughts. Thanks!
To quote MSDN
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
So you would have to define a class and select into that if you want read write capability.
e.g.
public class MyClass {
public int id { get; set; }
public string applicationCode {get; set; }
// rest of property defintions.
}
var query2 = context.applications.Select(c => new MyClass {
id = c.id,
applicationCode = c.applicationCode,
// Rest of assignments
};
As to just providing 10 character limit with ... appended. I'm going to assume you mean on the applicationcategoryLog field but you can use the same logic on other fields.
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
applicationCategoryLong = (c.applicationCategoryLong ?? string.Empty).Length <= 10 ?
c.applicationCategoryLong :
c.applicationCategoryLong.Substring(0,10) + "...",
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})

Change key in web.config to hold multiple values

I wish to change the web.config so that the key will hold multiple values:
i have now amended the code as suggested,
what should happen is that if the product SKU starts with either O-GREET or O-PEGC then a punchout module will launch, if not the product is added to basket as normal,
in the web.config file i have:
<add key="PunchOutOnSKUPrefix" value="O-GREET,O-PEGC"/>
and in the relevant controller (ShoppingCartCOntroller)
Extensions.PunchOut punchOut = new Extensions.PunchOut();
Boolean isPunchOut;
String id = productVariant.Sku;
String ticketId = null;
// Check that the product supports Punch out integration by looking at the first 3 letters of its SKU
if (String.IsNullOrWhiteSpace(id))
{
isPunchOut = false;
}
else
{
option = id.Substring(0, 7);
isPunchOut = ConfigurationManager.AppSettings["PunchOutOnSKUPrefix"].Split(',').DefaultOrNull(s => s.Equals(option));
}
Split returns an array of options, if you want to search for specific value, use:
var option = id.Substring(0, 7);
var isPunchOut = ConfigurationManager.AppSettings["PunchOutOnSKUPrefix"].Split(',').DefaultOrNull(s => s.Equals(option));
If you want to check if id starts with anyone of the values, use:
var isPunchOut = ConfigurationManager.AppSettings["PunchOutOnSKUPrefix"].Split(',').Any(s => id.StartsWith(s));

C# Coding issue with Drop Down List

First, let me tell you what error I am getting.
'DDLTesttoAppear' has a SelectedIndex which is invalid because it
does not exist in the list of items. Parameter name: value
I have many enums in my project, Here two enums are related two this question.
This Two enums are
public enum Gender
{
NA = 0, Male = 1, Female = 2
}
and
public enum NumberOfAdmissionTest
{
NA = 0, First = 1, Second = 2, Third = 3, Fourth =4
}
In UI page I have two DDls they are like
DDLGender.DataSource = Enum.GetNames(typeof(Gender));
DDLGender.DataBind();
DDLTestApearnce.DataSource = Enum.GetNames(typeof(NumberOfAdmissionTest));
DDLTestApearnce.DataBind();
This fields can be inserted as null into the database. Therefore, while returning the record I am using a null hander function
where the line of code to execute is that
candidateEntity.CandidateGender = nullHandler.GetInt32(CANDIDATE_GENDER);
candidateEntity.TestToAppear = nullHandler.GetInt32(TEST_TO_APPEAR);
public int GetInt32(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? 0 : _reader.GetInt32(_reader.GetOrdinal(sFieldName));
}
After retrieving the record, I am binding this with two ddls like
DDLGender.SelectedIndex = candidateEntity.CandidateGender;
DDLTesttoAppear.SelectedIndex = candidateEntity.TestToAppear;
Now, the interesting or confusing, whatever you say, part of this problem is that for gender, it's not generating any error, but for test appearance it's generating the error.
You are binding DDLTestApearnce in your sample, but are getting the error (and setting the selected value) on DDLTesttoAppear.

Is there a way to access the columns in a Dapper FastExpando via string or index?

I am pulling in a Dapper FastExpando object and want to be able to reference the column names dynamically at run time rather than at design/compile time. So I want to be able to do the following:
var testdata = conn.Query("select * from Ride Where RiderNum = 21457");
I want to be able to do the following:
foreach( var row in testdata) {
var Value = row["PropertyA"];
}
I understand that I can do:
var Value = row.PropertyA;
but I can't do that since the name of the property i'm going to need won't be known until runtime.
The answer from this SO Question doesn't work. I still get the same Target Invocation exception. So...
Is there any way to do what I want to do with a Dapper FastExpando?
Sure, it is actually way easier than that:
var sql = "select 1 A, 'two' B";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row["A"].IsEqualTo(1);
row["B"].IsEqualTo("two");
Regarding the portion of the title "or index?" - I needed to access results by index since the column names being returned changed sometimes, so you can use a variation of Sam Saffron's answer like this:
var sql = "select 1, 'two'";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row.Values.ElementAt(0).IsEqualTo(1);
row.Values.ElementAt(1).IsEqualTo("two");
There a simple way to access fields direct below sample
string strConexao = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
conexaoBD = new SqlConnection(strConexao);
conexaoBD.Open();
var result = conexaoBD.Query("Select Field1,Field2 from Table").First();
//access field value result.Field1
//access field value result.Field2
if (result.Field1 == "abc"){ dosomething}

Categories

Resources