Remove a property from list in C# - c#

hi i want to remove a property from list if a condition is true, my code is like below
foreach (var entry in entries)
{
var item = list
.BillingItems
.Select(x => new {
OrganizationId = entry.Organization,
OrganizationName = entry.Organization,
Revenue = entry.Revenue
});
}
Revenue// this property need to remove if condition is true
can i remove this withing new blocks

You can try this:
foreach (var entry in entries)
{
List<dynamic> item = new List<dynamic>();
foreach (var bi in List.BillingItem)
{
if (condition)
{
item.Add(new { entry.Organization, entry.Revenue });
}
else
{
item.Add(new { entry.Organization });
}
}
}
But, you are not using values from BillingItem and Im not sure if is your approach realy the right one

You can set it to null if condition ?
foreach (var entry in entries){
var item = list
.BillingItems
.Select(x => new {
OrganizationId = entry.Organization,
OrganizationName = entry.Organization,
Revenue = (condition) ? entry.Revenue : null
});
}

Related

How to simplify if condition and foreach condition in c#.net?

I have a repeating foreach condition in my controller. How can I simplify it?
I almost reach 500 lines because of this. I've been using this for x8 each condition.
List<jewelry_dashboard_view_per_month> transactionmonthlynewloan = dashboardmanager.Get_MonthlyTransaction(search_branch, (monthlyonly + "01"), "N-", (monthlyonly + no_of_items), no_of_items, monthlyonly);
myNewLoanMontlyList.Add(transactionmonthlynewloan);
List<jewelry_dashboard_view_per_month> transactionmonthlyrenewal = dashboardmanager.Get_MonthlyTransaction(search_branch, (monthlyonly + "01"), "R-", (monthlyonly + no_of_items), no_of_items, monthlyonly);
myRenewalMontlyList.Add(transactionmonthlyrenewal);
This is the if condition
if (myNewLoanMontlyList[0].Count != 0)
{
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.id_data))
{monthly_newloan_data_ID.Add(internal_monthly_newloan_data);}
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.debit_data))
{monthly_newloan_data_debit.Add(internal_monthly_newloan_data);}
}
else
{
monthly_newloan_data_ID.Add(0);
monthly_newloan_data_debit.Add(0);
};
and this is the foreach condition
//newloan
int newloan_data_id = 0;
DateTime newloan_data_transdate = DateTime.Parse((DateTime.Today).ToString());
decimal newloan_data_debit = 0;
string newloan_data_txnname = "";
string newloan_data_branchID = "";
foreach (var newloan_data in newloan)
{
newloan_data_id = newloan_data.ID;
newloan_data_transdate = DateTime.Parse((newloan_data.Transdate).ToString());
newloan_data_debit = Decimal.Parse((newloan_data.Debit).ToString());
newloan_data_txnname = newloan_data.TransactionName;
newloan_data_branchID = newloan_data.BranchID;
};
datanewloan = new transaction_details()
{
ID = newloan_data_id,
Transdate = DateTime.Parse(newloan_data_transdate.ToString("yyyy-MM-dd")),
Debit = Decimal.Parse(newloan_data_debit.ToString()),
TransactionName = newloan_data_txnname,
BranchID = newloan_data_branchID
};
In Your scenario of if-else conditions:
if (myNewLoanMontlyList[0].Count != 0)
{
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.id_data))
{monthly_newloan_data_ID.Add(internal_monthly_newloan_data);}
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.debit_data))
{monthly_newloan_data_debit.Add(internal_monthly_newloan_data);}
}
else
{
monthly_newloan_data_ID.Add(0);
monthly_newloan_data_debit.Add(0);
};
If in the method, there is no other process after the if-else, you can use only if condition without the else part.
if (myNewLoanMontlyList[0].Count == 0)
{
monthly_newloan_data_ID.Add(0);
monthly_newloan_data_debit.Add(0);
}
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.id_data))
{monthly_newloan_data_ID.Add(internal_monthly_newloan_data);}
foreach (var internal_monthly_newloan_data in myNewLoanMontlyList[0].SelectMany(c => c.debit_data))
{monthly_newloan_data_debit.Add(internal_monthly_newloan_data);}
You can use Linq,
SelectMany: Projects each element of a sequence to an IEnumerable<T>. You need not to iterate again and add it to separate list
For your if condition look like,
if (myNewLoanMontlyList[0].Any())
{
monthly_newloan_data_ID = myNewLoanMontlyList[0].SelectMany(c => c.id_data);
monthly_newloan_data_debit = myNewLoanMontlyList[0].SelectMany(c => c.debit_data);
}
else
{
monthly_newloan_data_ID.Add(0);
monthly_newloan_data_debit.Add(0);
}
Select: Projects each element of a sequence into a new form. In your
case new form is instance of transaction_details
Instead of for loop use Linq .Select(),
var result = newloan.Select(x => new transaction_details(){
ID = x.ID,
Transdate = DateTime.Parse(x.Transdate.ToString("yyyy-MM-dd")),
Debit = Decimal.Parse((x.Debit).ToString()),
TransactionName = x.TransactionName,
BranchID = x.BranchID
}).LastOrDefault();
To get last element, I used LastOrDefault(). You can get individual element by index or by condition.

How to assign "var" inside if statement

I need to do this:
var productsLocation = response.blah blah; //with linq query
var item; // even var item = null; //not valid
if(condition){
item = productsLocation.linq query
} else {
item = productsLocation.differentquery
}
var group = item.query;
Is this possible? If yes, how?
EDIT: here is my exact code:
var productLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
var items;
if (condition)
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
} else {
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}
If you look closely at the logic, you notice you don't actually even need the if block. The whole thing can be written in one expression as follows:
var items = productLocation
.Select(s => new ProductClass(s))
.Where(s => categories.Contains(s.CategoryName) && (condition || stocks.Contains(s.Barcode)));
First of all get your response variable type, then initialize 'item' variable as IEnumarable where T is same as response variable type
var productsLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
IEnumerable<ProductClass> item;
if (condition)
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
}
else
{
items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));
}
var group = item.Where(condition);
You can do it with IEnumerable interface in this way:
using System.Collections;
using System.Collections.Generic;
List<string> products = new List<string>() { "First", "Second", "Third", "Fourth" };
IEnumerable item;
var condition = false;
if (condition)
{
item = products.Select(x=>x);
}
else
{
item = products.Where(x => x.StartsWith("F"));
}
var group = item.Cast<string>().Where(/*...Here your conditions...*/)

Add/Update IEnumerable List

I just want to ask how can I pass/update an IEnumerable List that will be used to show in dropdown cause I am missing a set of lines to add it and update enumlist so that I can only get the Text and Value that is Arrived and Completed. Here is my Enumerable list in my Model
public enum DeliveryPermitStatus
{
Arrived = 1,
Approved = 2,
Cancelled = 3,
Completed = 4,
Submitted = 5
}
Code in my Controller so I can add the filtered enumlist and I am missing code to viewbag the updated enumlist that will be used to show in dropdown
var enumlist = Enum.GetValues(typeof(DeliveryPermitStatus)).Cast<DeliveryPermitStatus>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
});
if (User.IsInRole(StaticRoleNames.Admin)) //your condition here
{
foreach(var item in enumlist)
{
if(item.Text == "Arrived" || item.Text == "Completed")
{
//Missing Code Here
}
}
}
ViewBag.enumlist = enumlist;
I think what you are asking/wanting to do is edit the ViewBag.enumlist to be a reduced set of values based on a user's role? If so, then you could filter and assign the list inside your if statement and forego the foreach loop:
var enumlist = Enum.GetValues(typeof(DeliveryPermitStatus)).Cast<DeliveryPermitStatus>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
});
if (User.IsInRole(StaticRoleNames.Admin)) //your condition here
{
ViewBag.enumlist = enumlist.Where(t => t.Text == "Arrived" || t.Text == "Completed");
}
OR, if you need to keep the foreach loop, then you'll need to create a separate list to keep track of the "available values" for the enum list:
var enumlist = Enum.GetValues(typeof(DeliveryPermitStatus)).Cast<DeliveryPermitStatus>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
});
List<SelectListItem> availableOptions = new List<SelectListItem>();
if (User.IsInRole(StaticRoleNames.Admin)) //your condition here
{
foreach(var item in enumlist)
{
if(item.Text == "Arrived" || item.Text == "Completed")
{
availableOptions.Add(item);
}
}
}
ViewBag.enumlist = availableOptions;
You can't add elements to an IEnumerable, but you can easily get a List from it.
Just call ToList() before assign to your var enumlist.
Now you can add elements to it (be careful, don't add elements while enumerating it)

Entity Framework: How to insert data while looping through multiple lists

I am attempting to insert data from two List.
I am able to successfully insert from one List but adding the second list using a foreach loop does not work as expected.
How do I loop through each of these list so that I can insert their values?
Code:
private void InsertList()
{
var listA = new List<string>();
var listB = new List<string>();
//Populate both list by splitting items in listbox
foreach (ListItem item in ListBox1.Items)
{
var components = item.Value.Split('/');
listA.Add(components.First());
listB.Add(components.Last());
}
using (DataContext dataContext = new DataContext())
{
foreach (var itemA in listA)
{
foreach (var itemB in listB)
{
LIST_OBJECTS listObject = new LIST_OBJECTS
{
LIST_ITEM_A = itemA,
LIST_ITEM_B = itemB
};
dataContext.LIST_OBJECTS.Add(listObject);
}
}
dataContext.SaveChanges();
}
}
What about a for loop?
for (var i = 0; i < listA.Count; i++)
{
LIST_OBJECTS listObject = new LIST_OBJECTS
{
LIST_ITEM_A = listA[i],
LIST_ITEM_B = listB[i]
};
dataContext.LIST_OBJECTS.Add(listObject);
}
Since you know from the creation of the Lists that they'll have the same number of elements, this is fine.
You can do it with LINQ
LIST_OBJECTS listObject = listA.Join(listB,
a=>listA.Indexof(a),
b=>listB.Indexof(b),
(a,b)=> new LIST_OBJECTS()
{
LIST_ITEM_A =a,
LIST_ITEM_B =b
}).ToList();

Filtering a list in c#

So i have two lists .One is an Attorney object list and the other is a list with GUID .I am first just filling the GUID list with values and then looping through it and then matching it to the ID field of Attorney object to get the Attorney's with the given ID .
Is there a nicer way than my try to achieve this.
List<Attorney> Attorneys = msg.CaseDocument.Attorneys;
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();
foreach (var s in msg.CaseDocument.Defendants)
{
AttorneyID.AddRange(s.Attorneys);
}
foreach (var p in AttorneyID)
{
var z = Attorneys.FindAll(o => o.AttorneyId == p);
if (z != null)
{
CaseDefendantAtt.AddRange(z);
}
}
How about...
var caseDefendantAtt = msg.CaseDocument.Attorneys.Where(o =>
msg.CaseDocument.Defendants.SelectMany(d => d.Attorneys).Contains(o.AttorneyId));
Try this
var allAttorneyIds = msg.CaseDocument.Defendants.SelectMany(x=> x.Attroneys);
var caseDefendantsAtt = msg.CaseDocument.Attorneys.Where(x=> allAttorneyIds.Contains(x.AttorneyId)).ToList();
Maybe you could store your Attorneys in a Dictionary of [Guid, Attorney], then looking for each Guid in Dictionary.
Dictionary<Guid, Attorney> Attorneys = CreateDictionaryFrom(msg.CaseDocument.Attorneys);
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();
foreach (var s in msg.CaseDocument.Defendants)
{
AttorneyID.AddRange(s.Attorneys);
}
foreach (var p in AttorneyID)
{
var z = Attorneys[p];
if (z != null)
{
CaseDefendantAtt.Add(z);
}
}
It will increase the performance with the x1000 factor. But you should notice that we assume there is only one attorney per Guid.
Without using a dictionary, we could improve your search in list seeking for FirstOrDefault instead of FindAll

Categories