Add/Update IEnumerable List - c#

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)

Related

how to return list of list in c#?

I am working on web api.I am getting data from one table.
Data from database
DispatchData dta = new DispatchData();
using (SalesDataContext oSqlData4 = new SalesDataContext())
{
// amount paid -- not paid
var Amount_Paid = (from x in oSqlData4.Finances
where
(x.Order.Customer_ID.Equals("190") ||
x.Order.Customer_ID.Equals("1334"))
where (x.Status == "Not Approved")
select x).ToList();
foreach (var item in Amount_Paid)
{
dta.data = new string[] { item.Order_ID.ToString(), item.ID.ToString() };
}
var json = JsonConvert.SerializeObject(dta);
return json;
}
public class DispatchData
{
public string[] data ;
}
its returning me only one record
{"data":["2508","4684"]}
I want each row in array like this
{"data":[ ["2508","4684"],["2508","4684"],....] }
There's really not enough information in the question for a full answer, but with a few assumptions...
Assuming the SalesDataContext query returns an object, let's call it SalesPerson:
SalesPerson
Name (string)
Title (string)
Location (string)
Id (int)
Date (DateTime)
Sales (decimal)
With the above assumption, you can simply select each property as a string from the query result and throw it into an array:
var myList = Amount_Paid.Select(x =>
new[] {
x.Name,
x.Title,
x.Location,
x.Id.ToString(),
x.Date.ToString(), // add a format as needed
x.Sales.ToString() // add a format as needed
}
).ToArray();
return myList;
If you Really want a List:
var myList = Amount_Paid.Select(x =>
new List<string> {
x.Name,
x.Title,
x.Location,
x.Id.ToString(),
x.Date.ToString(), // add a format as needed
x.Sales.ToString() // add a format as needed
}
).ToList();
return myList;
The result can then be serialized as needed.
Edit
Based on the OP's edit, not much changes with the assumptions above. However, the OP's edit has two errors.
The foreach loop is overwriting dta.data.
The signature of data.data should be string[][], not string[].
Incorrect
public class DispatchData
{
public string[] data ;
}
foreach (var item in Amount_Paid)
{
dta.data = new string[] { item.Order_ID.ToString(), item.ID.ToString() };
}
Corrected
public class DispatchData
{
public string[][] data;
}
# can either predefine the size of the dta.data array,
# or just assign once the property can be materialized.
# Let's use the latter...
dta.data = Amount_Paid.Select(x =>
new[] {
item.Order_ID.ToString(),
item.ID.ToString()
}).ToArray();

Remove a property from list in 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
});
}

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...*/)

Query for selecting and anonymous object with where clause

This is my code:
var tree = new
{
id = "0",
item = new List<object>()
};
foreach ()
{
tree.item.Add(new
{
id = my_id,
text = my_name,
parent = my_par
});
}
But I want to replace the code in the foreach with the following:
foreach ()
{
tree.item.Where(x => x.id == 2).First().Add(new
{
id = my_id,
text = my_name,
parent = my_par
});
}
How to do this? I get exception that the type doesn't contain a definition for id.
The problem here is the anonymous type.
I tried creating a new class which would have 2 properties: id, text and parent and the syntax worked, but the tree's definition was invalid.
So the question here is how to make a query to an anonymous type, without adding a new class which would represent the anonymous type.
If you want to do it without creating a new class you can use dynamic for the filtering.
tree.item.Where(x => ((dynamic)x).id == 2).First()....
Although that will give you a single anonymous object and not a collection so you can not add anything to it.
One, this is really ugly. You should think of declaring a class for this (you got a downvote from some purist for this I assume ;))
Two, you're doing something that's impossible. Think about this, in your first loop, when you do tree.item.Where(x => x.id == 2).First(), you're getting x back, which is an object and object doesn't have an Add method. To illustrate, take this example:
var tree = new
{
id = "0",
item = new List<object>
{
new
{
id = 2,
text = "",
parent = null
}
}
};
Now when you do
var p = tree.item.Where(x => x.id == 2).First(); //even if that was compilable.
you are getting this
new
{
id = 2,
text = "",
parent = null
}
back. Now how are you going to Add something to that? It really is an anonymous type with no method on it.
I can only assume, but you might want this:
var treeCollection = new
{
id = 0,
item = new List<object> // adding a sample value
{
new // a sample set
{
id = 2,
text = "",
parent = null // some object
}
}
}.Yield(); // an example to make it a collection. I assume it should be a collection
foreach (var tree in treeCollection)
{
if (tree.id == 0)
tree.item.Add(new
{
id = 1,
text = "",
parent = null
});
}
public static IEnumerable<T> Yield<T>(this T item)
{
yield return item;
}
Or in one line:
treeCollection.Where(x => x.id == 0).First().item.Add(new
{
id = 1,
text = "",
parent = null
});

How to update a single item of liist of objects using LINQ in C#

I want like to update the Value of the list which has property Text="ALL".
public class Season
{
public string Text {get;set;}
public string Value {get;set;}
public bool ValueSelected {get;set;}
}
The 'Q' in LINQ stands for "Query". LINQ is not meant to update objects.
You can use LINQ to find the object you want to update and then update it "traditionally".
var toUpdate = _seasons.Single(x => x.Text == "ALL");
toUpdate.ValueSelected = true;
This code assumes that there is exactly one entry with Text == "ALL". This code will throw an exception if there is none or if there are multiple.
If there is either none or one, use SingleOrDefault:
var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL");
if(toUpdate != null)
toUpdate.ValueSelected = true;
If it's possible that there are multiple, use Where:
var toUpdate = _seasons.Where(x => x.Text == "ALL");
foreach(var item in toUpdate)
item.ValueSelected = true;
You could use something like this:
// Initialize test list.
List<Season> seasons = new List<Season>();
seasons.Add(new Season()
{
Text = "All"
});
seasons.Add(new Season()
{
Text = "1"
});
seasons.Add(new Season()
{
Text = "2"
});
seasons.Add(new Season()
{
Text = "All"
});
// Get all season with Text set to "All".
List<Season> allSeasons = seasons.Where(se => se.Text == "All").ToList();
// Change all values of the selected seasons to "Changed".
allSeasons.ForEach(se => se.Value = "Changed");

Categories