How to update a List in C# - c#

IList<ReceiptAllocationMaster> objReceiptMaster = (IList<ReceiptAllocationMaster>)Session["AllocationResult"];
public class ReceiptAllocationMaster
{
public string application { get; set; }
public List<Users> users { get; set; }
}
public class Users
{
public string name { get; set; }
public string surname { get; set; }
}
I need to Update the above list with some value where application = "applicationame" and users where surname = "surname" into the same list.

Just iterate over your list and modify matched items:
for (int i = 0; i < objReceiptMaster.Count; i++)
{
var item = objReceiptMaster[i];
if (item.application == "applicationname" && item.users.Any(x => x.surname == "surname"))
objReceiptMaster[i] = new ReceiptAllocationMaster();
}
Instead of new ReceiptAllocationMaster() you can write any modification data logic.

though your question is not clear, this shd give u some idea:
objReceiptMaster.Where(x=>x.application=="applicationname" &&
x.users.Any(d=>d.surname=="surname"))
.ToList()
.ForEach(item=>{//update your list
item.application = "whatever value";
item.users.ForEach(user=>{//update users
user.name="whatever username";
});
});

Related

Bind List instead list c# linq From multiple source

i have my dto
public class DocumentForListDto
{
public int Id { get; set; }
public string Title { get; set; }
public string SubmittedBy { get; set; }
public DateTime SubmittedAt { get; set; }
public List<AuditsUpdateForListDto> UpdatedDocuments { get; set; }
}
public class AuditsForListDto
{
public string FullName { get; set; }
public DateTime UpdatedAt { get; set; }
}
and this code in my controller :
var docs = await _repo.Doc.Get();
and i have this audit to save any action in database
var aud = await _repo.Audit.FindByPrimaryKey(Constants.Doc, documents.Select(x => x.Id).ToList());
and this mapper for map my doc to dto(content)
var contents = _mapper.Map<IEnumerable<DocumentForListDto>>(docs);
and this my foreach to bind from audit to contents (CreatedBy/CreatedAt && UpdateBy/UpdatedAt)
if (contents.Any() && contents.Count() > 0 && audits.Any() && audits.Count()
> 0)
{
foreach (var content in contents)
{
//Search here by create Action
foreach (var audit in audits.Where(x =>
Convert.ToInt32(Regex.Match(x.PrimaryKey, #"\d+").Value) ==
content.Id && x.Type.Equals(Constants.Create)))
{
content.SubmittedBy = string.Concat(audit.User.FirstName, " ",
audit.User.LastName);
content.SubmittedAt = audit.DateTime;
}
}
//Here I need to bind list of Updated By and Updated At But I try many times but I don't find the right solution
}
i need to bind list of Updated By and Updated At i try with many logics but without success ??

Filter based on a string value in List<string> column in a table Entity Framework Core

I have a table with the following structure (code first approach using Entity Framework Core) in PostgreSQL
public class Product_Order
{
[Key]
public string product_number { get; set; }
public string customer_product_number { get; set; }
public List<string> product_statuses { get; set; }
public bool is_test { get; set; } = false;
public DateTime created_at { get; set; } = DateTime.UtcNow;
public DateTime updated_at { get; set; } = DateTime.UtcNow;
public string created_by { get; set; } = "system";
public string updated_by { get; set; } = "system";
}
Now, the product_statuses column usually contains of a list of statuses - ready, pickedup, scheduled, closed, cancelled.
I need to come up with a solution which returns me a list of product orders which DOES NOT CONTAIN orders which are closed or cancelled.
Here's the solution that I have at the moment which is not filtering as expected
_context.Product_Order.Where(t => t.is_test && !t.statuses.Contains("closed") && !t.statuses.Contains("cancelled")).ToList();
I think your code is ok for your data structure to find that information. I have created a dummy class and list to replicate your data and list. And I was able to find data by using you code. Sample Code given below what I have tested =>
void Test()
{
List<Product_Order> items = new List<Product_Order>();
var temp = new Product_Order() { product_number = "001", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("good");
temp.product_statuses.Add("greate");
temp.product_statuses.Add("new");
items.Add(temp);
temp = new Product_Order() { product_number = "002", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("good");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("notnew");
items.Add(temp);
temp = new Product_Order() { product_number = "003", isTest = true };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("n/a");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("Closed");
items.Add(temp);
temp = new Product_Order() { product_number = "004", isTest = false };
temp.product_statuses = new List<string>();
temp.product_statuses.Add("n/a");
temp.product_statuses.Add("bad");
temp.product_statuses.Add("Cancelled");
items.Add(temp);
var finalOutput = items.Where(c => c.isTest == true && !c.product_statuses.Where(v => v.ToLower() == "closed").Any() && !c.product_statuses.Where(v => v.ToLower() == "cancelled").Any()).ToArray();
}
public class Product_Order
{
public string product_number { get; set; }
public bool isTest { get; set; }
public List<string> product_statuses { get; set; }
}
Finally , I think it is your data what not wright with you lambda expression. So, I modified for you a little bit.And that is
FINAL ANSWER:
var finalOutput = _context.Product_Order.Where(c => c.isTest == true && !c.product_statuses.Where(v => v.ToLower() == "closed").Any() && !c.product_statuses.Where(v => v.ToLower() == "cancelled").Any()).ToArray();
Please check my code and let me know.

Cannot convert type list.<string> to string error

I have a controller method that looks like this
//cycles through sites in order to populate variables
foreach (Site s in sites)
{
foreach (OffSiteItemDetails d in s.ItemDetails)
{
if (d.itemID != null)
{
osiItemCost[s.ID] = d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, false);
osiLoItemCost[s.ID] += d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, true);
osiItemLastCost[s.ID] += db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(d.qty, true, false);
}
}
}
o it generates a value for each variable for example osiItemCost[s.ID] could equal 0 for one site ID but it could equal 70 for another Site
So I am trying to create a table for each site ID. Currently if I leave it like
model.OffReportColumns = new List()
It will just keep getting overwritten by the next site Id in the list. So I am trying to assign the list to the sites ID.
foreach (Site s in sites)
{
foreach (OffSiteItemDetails d in s.ItemDetails)
{
model.OffReportColumns[s.ID] = new List<string>()
{
s.Name,
"",
"",
"Average Cost",
"",
"",
"Average Cost (With labour)"
};
Here is my Model class
public class SummaryReportModel
{
public string Title { get; set; }
public string ReportTitle { get; set; }
public string OffReportTitle { get; set; }
public List<string> ValuationColumns { get; set; }
public List<string> OffReportColumns { get; set; }
public List<List<string>> ValuationRows { get; set; }
public List<List<string>> OffReportRows { get; set; }
public List<List<string>> Total { get; set; }
public List<List<string>> OffReporTotal { get; set; }
public List<List<string>> Tital { get; set; }
public List<List<string>> SecondTital { get; set; }
public List<List<string>> osiGrandTotal { get; set; }
}
Where s.ID represents a "site ID"
Currently I receive the errors
Cannot implicitly convert type
'systems.collections.generic.List' to 'string'
However, it works when I remove the [s.ID] so that it looks like this
model.OffReportColumns = new List<string>()
Why is the s.ID causing an issue?
When you use model.OffReportColumns[s.ID] you are referencing the individual string with an index of s.ID. When you use model.OffReportColumns you are referencing the entire list.
You cannot set model.OffReportColumns[s.ID] equal to new List<string>() because a List<string> is not a string
Is not really clear what you are trying to do here. It seems that OffReportColumns is a list of strings, and you are trying to add a list a string to a certain index of it.
If you do this
model.OffReportColumns.AddRange(new List<String>(){
s.Name,
"string test",
"etc."
})
You will add all items of your new list of strings to the end of OffReportColumns.

How retrieve value from string collections in c#

I have a collection defined by:
public class CompanyModel
{
public string compnName { get; set; }
public string compnAddress { get; set; }
public string compnKeyProcesses { get; set; }
public string compnStandards { get; set; }
}
Then I stored names and addresses to this collection from a data table:
List<CompanyModel> companies = new List<CompanyModel>();
for(int i = 0; i < dt.Rows.Count; i++)
{
companies.Add(new CompanyModel
{
compnName = dt.Rows[i]["companyName"].ToString(),
compnAddress = dt.Rows[i]["address"].ToString()
});
}
My question is how could I retrieve each compnName from that collection ?
I tried this
foreach (CompanyModel company in companies)
{
string compnyName = company.compnName;
But it return me blank result.
The simplest option would be to use LINQ, e.g.
var names = companies.Select(c => c.compnName);

RavenDb how do I reduce group values into collection in reduce final result?

I hope it's more clear what I want to do from the code than the title. Basically I am grouping by 2 fields and want to reduce the results into a collection all the ProductKey's constructed in the Map phase.
public class BlockResult
{
public Client.Names ClientName;
public string Block;
public IEnumerable<ProductKey> ProductKeys;
}
public Block()
{
Map = products =>
from product in products
where product.Details.Block != null
select new
{
product.ClientName,
product.Details.Block,
ProductKeys = new List<ProductKey>(new ProductKey[]{
new ProductKey{
Id = product.Id,
Url = product.Url
}
})
};
Reduce = results =>
from result in results
group result by new {result.ClientName, result.Block} into g
select new BlockResult
{
ClientName = g.Key.ClientName,
Block = g.Key.Block,
ProductKeys = g.SelectMany(x=> x.ProductKeys)
};
}
I get some weird System.InvalidOperationException and a source code dump where basically it is trying to initialize the list with an int (?).
If I try replacing the ProductKey with just IEnumerable ProductIds (and make appropriate changes in the code). Then the code runs but I don't get any results in the reduce.
You probably don't want to do this. Are you really going to need to query in this manner? If you know the context, then you should probably just do this:
var q = session.Query<Product>()
.Where(x => x.ClientName == "Joe" && x.Details.Block == "A");
But, to answer your original question, the following index will work:
public class Products_GroupedByClientNameAndBlock : AbstractIndexCreationTask<Product, Products_GroupedByClientNameAndBlock.Result>
{
public class Result
{
public string ClientName { get; set; }
public string Block { get; set; }
public IList<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public string Id { get; set; }
public string Url { get; set; }
}
public Products_GroupedByClientNameAndBlock()
{
Map = products =>
from product in products
where product.Details.Block != null
select new {
product.ClientName,
product.Details.Block,
ProductKeys = new[] { new { product.Id, product.Url } }
};
Reduce = results =>
from result in results
group result by new { result.ClientName, result.Block }
into g
select new {
g.Key.ClientName,
g.Key.Block,
ProductKeys = g.SelectMany(x => x.ProductKeys)
};
}
}
When replicating I get the same InvalidOperationException, stating that it doesn't understand the index definition (stack trace omitted for brevity).
Url: "/indexes/Keys/ByNameAndBlock"
System.InvalidOperationException: Could not understand query:
I'm still not entirely sure what you're attempting here, so this may not be quite what you're after, but I managed to get the following working. In short, Map/Reduce deals in anonymous objects, so strongly typing to your custom types makes no sense to Raven.
public class Keys_ByNameAndBlock : AbstractIndexCreationTask<Product, BlockResult>
{
public Keys_ByNameAndBlock()
{
Map = products =>
from product in products
where product.Block != null
select new
{
product.Name,
product.Block,
ProductIds = product.ProductKeys.Select(x => x.Id)
};
Reduce = results =>
from result in results
group result by new {result.Name, result.Block}
into g
select new
{
g.Key.Name,
g.Key.Block,
ProductIds = g.SelectMany(x => x.ProductIds)
};
}
}
public class Product
{
public Product()
{
ProductKeys = new List<ProductKey>();
}
public int ProductId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public string Block { get; set; }
public IEnumerable<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public int Id { get; set; }
public string Url { get; set; }
}
public class BlockResult
{
public string Name { get; set; }
public string Block { get; set; }
public int[] ProductIds { get; set; }
}

Categories

Resources