I have a problem in getting the values for the below.
I have a table called Retailers which contains Id,Description,Language and Code
I declared a list in my application which contains all the retailers list
var retailers = new List<Retailer>();
Now I need to add results of two retailers with same code so I am trying to do below and I am sure I am doing something wrong.
foreach (var retailer in retailers)
{
if (retailer.LanguageId != null)
{
// Here I am trying to findout if there are any other retailers who
// has same code if true then I need entire row of that retailer
**var retailerWithSameUacode = !retailers.Select(item => item.Code == retailerCode).SingleOrDefault();**
if (retailerWithSameUacode != null)
{
// Do something
}
}
}
Any help is much appreciated !
I don't think I entirely understand your question, but from your code comment and your attempt to select a retailer with the same code, I present to you the following..
To get the first retailer out of your list with a code that matches the current retailer, you would need to do this:
Retailer retailerWithMatchingCode = retailers.Where(r => r.Code == retailer.Code).FirstOrDefault();
You can then check the retailerWithMatchingCode object for a null value. If you just want to know if a retailer with a matching code exists, this is what you would do:
if (retailers.Any(r => r.Code == retailer.Code))
//Do something..
To get a list of retailers who have a matching "Code" property value, you would need to do this:
List<Retailer> retailersWithMatchingCode = retailers.Where(r => r.Code == retailer.Code).ToList();
Please note that this code is untested.
Try this solution:
var retailerWithSameUacode = retailers
.Where(item => item.LanguageId != null && item.Code == retailerCode)
.ToList();
foreach (var item in retailerWithSameUacode)
{
// Do something
}
Related
I have a object called Items. I use that object like so.
List<List<Items>> myItems = new List<List<Items>>();
I want to know how to get a specific List<Items> out of the List<List<Items>> object. Currently I am using foreach loops with some rules to find a specific List<Items>
This is currently what I am doing
foreach (List<Items> db2Items in db2Data)
{
foreach (List<Items> apiItems in apiData)
{
if (db2Items[0].Value == apiItems[0].Value && db2Items[27].Value == apiItems[27].Value)
{
/// Some other logic here
}
}
}
I was wanting to use LINQ to get the matching List<items> out of apiData and if I have a result then do the logic I wanted to do.
Not really sure what you're trying to accomplish, but if you want to get a list in a list based on a certain condition you can do it like this:
var item = db2Data.Where(x => x.Where(y => y.[value] == [YourCondition]).Any()).FirstOrDefault();
the "x.Where(y => y == [YourCondition]).Any()" will return true if the condition is met, and firstordefault will then return the list that meets the condition.
I have figured it out.
Using LINQ:
foreach (List<Items> db2Items in db2Data)
{
IEnumerable<List<Items>> theItem = from item in apiData
where item[0].Value == db2Items[0].Value && item[27]>Value == db2Items[27].Value
select item;
if (theItem.ToList().Count > 0)
{
// Do something
}
}
Ok so I'm trying to get all items which have been shipped and add them to a list if the shipment item is not already in that list. But if the shipment item is found in the list then I want to combine those two items in the list.
Here is the code I'm working with:
var shippedItems = _orderService.GetOrderById(shipment.OrderId).Shipments.Where(x => x.ShippedDateUtc != null && x.OrderId == shipment.OrderId && x.Id != shipment.Id).ToList();
List<ShipmentItem> shipmentItemsList = new List<ShipmentItem>();
for (int i = 0; i <= shippedItems.Count - 1; i++)
{
var si = shippedItems[i];
var sii = si.ShipmentItems.ToList();
foreach (var item in sii)
{
if (!shipmentItemsList.Contains(item))
{
shipmentItemsList.Add(item);
}
else
{
var foundId = shipmentItemsList.Select(x => x.Id == item.Id);
shipmentItemsList.Aggregate((foundId, item) => foundId + item);
}
}
}
For these two variables (foundId, item) i get errors:
A local variable named the variable name cannot be declared in this
scope because that name is used in an enclosing local scope to define
a local or parameter
UPDATE
I also thought I could try the following, but it's not joining the results.
if (i == 0)
{
shipmentItemsList = si.ShipmentItems.ToList();
}
else
{
shipmentItemsList.Concat(si.ShipmentItems.ToList());
}
Anyone able to point me on the right track.
Cheers
Thanks for the clarification. Essentially, the way that I understand your problem is that you need to take an object map that is grouped by Shipment and look at it from the point of Item instead. Linq can deal with this for you by using SelectMany to flatten the list and the GroupBy to shape the flattened list into your new groupings. I've made some assumptions about property names for the nopCommerce objects, but the following code sample should get you close enough to tweak with the correct property names:
var shipmentItemsList = shippedItems // This is logically grouped by shipment id
.SelectMany(s => s.ShipmentItems) // First flatten the list
.GroupBy(i => i.ItemId) // Now group it by item id
.Select(g => new
{
ItemId = g.Key,
Quantity = g.Sum(item => item.Quantity)
}) // now get the quantity for each group
.ToList();
I have a C# WinForms application. There is a listbox filled with values in this format:
category:user:id
Food:tester:17
etc.
Now, I need to get if an item is included in this Listbox, knowing only the category and ID, I don't know the user. So technically, I need to do something like this (pseudocode):
if(MyListBox.Items.Contains("Food:*:17"))
where the * would mean "anything". Is there a way of doing this?
Assuming the listbox is filled directly with strings, the easiest way would be a combination of linq and regex:
if(MyListBox.Items.Cast<string>().Any(s => Regex.IsMatch(s, "Food:.*:17"))) //(For RegEx: using System.Text.RegularExpressions )
or more strict, if the items are always a combination of value:value:value and you only check the first and third value:
if (MyListBox.Items.Cast<string>().Any(s => { var values = s.Split(':'); return values[0] == "Food" && values[2] == "17"; }))
You could do something like
var value = MyListBox.Items.Cast<string>()
.FirstOrDefault(m => m.Contains("Food:") && m.Contains(":17"));
if (value != null) {
// you have a match
}
try something like this
var res =
MyListBox.items.SingleOrDefault(
item =>
item.Contains("Food:") && item.Contains(":17") &&
item.IndexOf(":17", StringComparison.InvariantCulture) >
item.IndexOf("Food:", StringComparison.InvariantCulture));
if ( !string.IsNullOrEmpty(res))
{
//your code here
}
}
Data1 = new ObservableCollection<dsData1>(from itmGetAllData2 in GetAllData2
where itmGetAllData2.Name == strName
select itmGetAllData2)[0];
Above LINQ is working fine if there is a match between itmGetAllData2.Name == strName but if there is no record matching strName it is throwing an error.
Can anyone suggest how to handle this? I tried doing
.DefaultIfEmpty().Max(itmGetAllData2 => itmGetAllData2 == null ? "" : itmGetAllData2);
but it's giving casting error.
Your code could be simplified to:
Data1 = GetAllData2.FirstOrDefault(x => x.Name == strName);
If no matches are found, Data1 will be null. (that's what the OrDefault part adds) If you want to substitute a different value for null, you can do, e.g.
Data1 = GetAllData2.FirstOrDefault(x => x.Name == strName) ?? new dsData1();
The reason you are getting this error is because you are trying to access the first element of an empty query.
Use FirstOrDefault
var result = GetAllData2.FirstOrDefault(ad => ad.Name = strName);
if (result != null)
{
// Initalize your ObservableCollection here
}
You get this error when there is no match because [0] is trying to access the first object of a list that doesn't have any objects. Do this instead:
Data1 = GetAllData2.FirstOrDefault(d => d.Name == strName);
This will be the first item like you want, or null if none were found.
I have these 2 forms (Add.aspx) "CalculationParameters" and "CalculationParametersValues". I also have 2 forms (Delete.aspx). These two forms are related. If there is no CalculationParameter, then you cannot add CalculationParametersValues. Now my problem is... when I delete a CalculationParameter, I want to check first if the CalculationParammeter has any CalculationParametersValues. I need to do this using this "=>" which is new to me, but I can't get the hang of it.
I get the values from database from here : "Factory.Definitions.CalculationParameters.List()" and "Factory.Definitions.CalculationParametersValues.List()".
It should be something like this (I think):
Factory.Definitions.CalculationParameters.List(item => (item.Id == <NOW here is where I should equal that Id with "CalculationParameterId">)
Help please ?
Assuming that you know which CalculationParameter is deleting and it's Id the solution will be:
var paramValues = Factory.Definitions.CalculationParametersValues.Where(p => p.Id == calculationParameter.Id);
Suggest reading this MSDN article. It is short and clear with nice examples for beginners.
// Add New Item
If (Factory.Definitions.CalculationParameters.List().Where(item => item.ID == NewItem.ID).Count == 0)
{
// Add new item to list
Factory.Definitions.CalculationParametersValues.List().Add(NewItem);
}
// Delete item
If (Factory.Definitions.CalculationParametersValues.List().Where(item => item.ID == DeleteItem.ID).Count == 0)
{
// No record in Values list ... Do something here
}
else
{
// Some records in Values list .. Do something here
}