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 3 years ago.
Improve this question
want to remove foreach loop and done with Linq....Please suggest
In ViewModal I have LeadStatus Name and in LeadModal i have Id of LeadStatus on basis of Id I have to fatch Name from LeadStatusTable and bind in ViewModal
Thanks
List<Entities.LeadViewModel> leadViewModels = new List<Entities.LeadViewModel>();
IEnumerable<Entities.Lead> leads = await _leadRepository.AllNonDeletedAndConvertedLeads();
foreach (var lead in leads)
{
Entities.ChetuUser chetuUser = await _chetuUserRepository.GetChetuUser(lead.OwnerId);
if (!string.IsNullOrEmpty(lead.Status))
{
LeadStatusMaster leadStatusMaster = await _masterTableRepository.LeadStatusMasterById(lead.Status);
if (chetuUser != null && leadStatusMaster != null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = leadStatusMaster.Name,
CreatedDate = lead.CreatedDate
});
}
else if (chetuUser != null && leadStatusMaster == null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate
});
}
else
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate,
OwnerName = ""
});
}
}
else
{
if (chetuUser != null)
{
leadViewModels.Add(new Entities.LeadViewModel
{
LeadProperty = lead,
LeadStatusName = "",
CreatedDate = lead.CreatedDate,
OwnerName = chetuUser.EmployeeName
});
}
}
}
return leadViewModels;
Your title is different by the asked question. Because you speak about the speed replaceing the foreach with linq will not speed up your loop. The problem is the awaits in it. Moreover the linq's foreach is a little tricky to work with await:
C# async await using LINQ ForEach()
Related
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 3 years ago.
Improve this question
In C# I am passing a single string value to a function. The value is similar to this: "XA=12345678;BK=AZ31" or "XA=87654321", sometimes the BK= is there, sometimes it is not. But if it's present, I need it for my function.
I've made this attempt:
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
string XA_EQ = "";
string BK_EQ = "";
foreach(string item in item_list)
{
BK_EQ = "";
string[] split = item.Split(';');
XA_EQ = split[0];
if(split.length == 2)
BK_EQ = split[1];
my_func(XA_EQ, BK_EQ);
}
Is there a better way to do this? This works, but it seems inconvenient.
RegEx approach
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach (string item in item_list)
{
string XA_EQ = Regex.Match(item, "(?<=XA=)[0-9A-Z]*").Value;
string BK_EQ = Regex.Match(item, "(?<=BK=)[0-9A-Z]*").Value;
my_func(XA_EQ, BK_EQ);
}
https://dotnetfiddle.net/6xgBi3
I suggest Splitting initial strings into Dictionary:
using System.Linq;
...
private static Dictionary<string, string> GetVariables(string source) {
return source
.Split(';')
.Select(pair => pair.Split('='))
.ToDictionary(pair => pair[0].Trim(), pair => pair[1].Trim());
}
Now we can analyze values:
string[] item_list = new string[] { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list) {
var namesAndValues = GetVariables(item);
// If we have XA variable, assign its value to XA_EQ, otherwise assign ""
string XA_EQ = namesAndValues.TryGetValue("XA", out string xa) ? xa : "";
// If we have "BK" variable, call my_func with it
if (namesAndValues.TryGetValue("BK", out string BK_EQ)) {
// If we have "BK" variable
my_func(XA_EQ, BK_EQ);
}
}
Easy to read solution with LINQ:
string[] itemList = { "XA=12345678;BK=AZ31", "XA=87654321" };
itemList.Select(x => x.Split(";")).ToList().ForEach(i =>
{
string XA_EQ = i.FirstOrDefault();
string BK_EQ = i.Skip(1).FirstOrDefault();
my_func(XA_EQ, BK_EQ != null ? BK_EQ : "");
});
You don't get the actual value of XA or BK this way, but since you mention that this works for you I'm implementing the same logic.
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list)
{
if item.Contains('BK') {
string[] split = item.split(';');
my_func(split[0], split[1]);
} else {
my_func(item, null);
}
}
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 5 years ago.
Improve this question
Check the code bellow. I am looping to get all value of a returned XML response. But i want to get a total value of all nofwatch variable. How can i add them to get a total value? any idea?
foreach (var sri in searchResultItems)
{
// Get all xml elements
var childElements = sri.Elements();
var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
.Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");
//add items from xml data to EbayDataViewModel object
items.Add(new EbayDataViewModel
{
TotalWatchers = nofwatch.Value //how can do + result of all nofwatch value?
});
ViewBag.TotalWatchers = TotalWatchers;
}
var totalValue = 0; //delcare the variable outside the foreach loop
foreach (var sri in searchResultItems)
{
// Get all xml elements
var childElements = sri.Elements();
var nofwatch = childElements.FirstOrDefault(x => x.Name.LocalName == "listingInfo")
.Elements().FirstOrDefault(x => x.Name.LocalName == "watchCount");
//now use += operator to add the result to the totalValue variable
//totalValue += nofwatch.Value;
//nofwatch.Value should be of type string and you would need to parse it as an integer first if that truely is the case
var intValue = 0;
if (int.TryParse(nofwatch.Value, out intValue) == false)
continue;
totalValue += intValue;
}
//outside of the foreach loop use totalValue to set the desired member
ViewBag.TotalWatchers = totalValue;
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 6 years ago.
Improve this question
The method looks as following:
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
var result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
return result;
}
}
It's obvious that not all paths return something and the issue is I can't return null.
How to rearrange the method?
Maybe you can initialize your List?
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
List<string> result = new List<string>()
{
owner,
string.Empty,
string.Empty
};
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
}
return result;
}
I usually do this when I want to create an assembler method for example to tranform a List<X> to another List<Y>, so if my List<X> is null I try to return an empty List of Y. I prefer to do this instead of throwing exceptions and getting my Dashboard full of errors. But It depends on how your codes works.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The forum is full of posts about problems like this. I've red some but didn't manage to solve my own problem.
I get Exception error:
Object reference not set to an instance of an object.
try
{
CZaposleni zap = new CZaposleni();
zap.Sifra = "1234567894567";
zap.Ime = "testIme";
zap.Prezime = "testPrezime";
zap.Pol = Char.Parse("M");
zap.JMBG = "1234567899871";
zap.Brknjizice = "12345";
zap.SS = "4.test";
zap.DatumR = DateTime.Parse("4/11/2013");
zap.DatumZ = DateTime.Parse("4/11/2013");
zap.Mestorodj = "testMesto";
zap.Prebivaliste = "testPrebivaliste";
zap.Kontakt1 = "654987";
zap.Kontakt2 = "564845";
CRadnaMesta rad = new CRadnaMesta();
rad.ID = Int32.Parse(cbRadnaMesta.SelectedValue.ToString());
Console.WriteLine("Zap = "+zap.ID +" Rad = "+rad.ID);
zap.Radnomesto = rad;
Console.WriteLine("Zap check 1: " + zap.ID + " " + zap.Radnomesto.ID);
zap.dodajRadnika();
Console.WriteLine("Zap check 2: "+zap.ID+" "+zap.Radnomesto.ID);
}
catch (Exception ex)
{
MessageBox.Show("Frm: "+ex.Message);
}
The code breaks at 'zap.Radnomesto = rm;' since last output when running the code i get is
rm.ID = 1
zap.ID = 0
So none of two objects is null.
I believe your error is in the CZaposleni class in the following code:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( radnomesto.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}
More precisely in if ( radnomesto.ID == 0 ). Since radnomesto is null if not set, you're getting the error while checking for the ID.
You should use the following code instead:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( value == null || value.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}
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 9 years ago.
Improve this question
Is it possible to transform following code to Linq that it will look like little bit more nicely
foreach (var entry in bottleneck.Item2)
{
if(entry.ChangeoverTime > 0)
{
avarangechangeOverTimes += entry.ChangeoverTime;
++counter;
}
if (entry.ChangeoverTime > maxchangeOverTimes)
{
maxchangeOverTimes = entry.ChangeoverTime;
}
changeovertime.ChangeoverTimes.Add
(
new ChangeOverDateValue
{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}
);
}
If the number of entries in bottleneck.Item2 isn't huge, you could achieve the same using these three statements:
var maxChangeOverTime = bottleneck.Item2.Max(x => x.ChangeoverTime);
var averageChangeOverTime = bottleneck.Item2.Average(x => x.ChangeoverTime);
var result
= bottleneck.Item2
.Select(x => new ChangeOverDateValue
{
ChangeoverValue = x.ChangeoverTime,
Color = ChangeOverTimeToColor(x.ChangeoverTime),
StartTime = x.StartTime
});
changeovertime.ChangeoverTimes.AddRange(result);
Please note that this will enumerate bottleneck.Item2 three times instead of one time with your current code.
I think that you can only change the external foreach:
bottleneck.Items2.ToList().Foreach(entry =>
{
// your code
});
bottleneck.Item2.where(entry => entry.ChangeoverTime).ToList().Foreach(entry => {
avarangechangeOverTimes += entry.ChangeoverTime;
++counter;
});
maxchangeOverTimes = bottleneck.Item2.max=(entry => entry.ChangeoverTime);
changeovertime.ChangeoverTimes.AddAll(bottleneck.Item2.select(entry => new new ChangeOverDateValue
{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}));
this is all i can come up with without having more info or my development envirment with me
Maybe...
var avarangechangeOverTimes = bottleneck.Item2
.Where(entry => entry.ChangeOverTime > 0)
.Sum(entry => entry.ChangeOverTime);
var maxchangeOverTimes = bottleneck.Item2
.Max(entry => entry.ChangeOverTime);
bottleneck.Item2.ToList()
.ForEach(entry => changeovertime.ChangeoverTimes.Add
(
new ChangeOverDateValue {
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
}
)
);
Try this:
var averagechangeOverTimes = bottleneck.Item2
.Where(entry => entry.ChangeoverTime > 0)
.Sum(entry => entry.ChangeoverTime);
counter = bottleneck.Item2.Count(entry => entry.ChangeoverTime > 0);
var maxchangeOverTimes = bottleneck.Item2.Max(entry => entry.ChangeoverTimes);
changeovertime.ChangeoverTime.Add(bottleneck.Item2
.Select(entry => new ChangeOverDateValue{
ChangeoverValue = entry.ChangeoverTime,
Color = ChangeOverTimeToColor(entry.ChangeoverTime),
StartTime = entry.StartTime
});