Predicate is not stacking in foreach loop - predicate

In the following code, predicate is not stacking in foreach loop and the results are not returned.
foreach (var item in rProfilesids)
{
if (typeid=="3")
{
predicate = predicate.And(z => pTypes.Contains(z.PTypeId.ToString()));
}
}
int lst = query.Where(predicate).Select(x => x.PartId).Distinct().ToList().Count();
Any suggestions?

Related

how to return the result outside the if statement

I was writing a revit pluging using c#. I couldn't return the result without assign public variable. Below is my code.I am not sure what is the error. Error in last codeline - return stid
public ElementId sysid(Duct elt, Document doc)
{
ElementId stid;
FilteredElementCollector DuctSystemcollector = new FilteredElementCollector(doc);
ICollection<Element> DuctSystem = DuctSystemcollector.OfClass(typeof(MechanicalSystemType)).ToElements();
foreach (Element j in DuctSystem)
{
string sn = j.GetParameters("Type Name")[0].AsString();
if (sn == elt.GetParameters("System Type")[0].AsValueString())
{
stid = j.Id;
//return stid;
//TaskDialog.Show("Duct shape ", stid);
}
}
return stid;
}

Why are we doing so in nested foreach loop? I can't understand I am lost

I can't grasp the nested foreach loop. Anyone to simplify this for me? I am learning foreach loops in C# but am stuck. What is the logic behind this?
class SudokuFileReader
{
public int[,] ReadFile(string fileName)
{
int[,] sudokuBoard = new int[9, 9];
try
{
var sudokuBoardLines = File.ReadAllLines(fileName);
int row = 0;
foreach (var sudokuBoardLine in sudokuBoardLines)
{
string[] sudokuBoardLineElements = sudokuBoardLine.Split('|').Skip(1).Take(9).ToArray();
int col = 0;
foreach (var sudokuLineElement in sudokuBoardLineElements)
{
sudokuBoard[row, col] = sudokuLineElement.Equals(" ") ? 0 : Convert.ToInt16(sudokuLineElement);
col++;
}
row++;
}
}
catch (Exception ex)
{
throw new Exception("Something went wrong while reading the file: " + ex.Message);
}
return sudokuBoard;
}
}

Difference between Java and Kotlin for-loop syntax?

I recently started learning Kotlin and the one thing I noticed is the for-loop syntax of Kotlin is different from traditional for-loop syntax and for me it is a bit confusing...I tried to search it on google but didn't get my answer.
How would I duplicate the following Java for loop?
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
Here is a Java for loop to iterate 100 times:
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
Here is the Kotlin equivalent:
for (i in 0..100) {
println(i)
}
Here is a Java for loop that will iterate through a list:
for (int i = 0; i < list.size(); i++) {
Object item = list.get(i);
// Do something with item
}
Kotlin equivalent:
for (i in list.indices) {
val item = list[i]
// Do something with item
}
Here is another Kotlin equivalent for iterating a list:
for (i in 0 until list.size) {
val item = list[i]
// Do something with item
}
Java for-each loop:
for (Object item : list) {
// Do something with item
}
Kotlin for-each loop:
for (item in list) {
// Do something with item
}
val scanner = Scanner(System.`in`)
var nos = Array<Int>(5) { 0 }
for (i in 1..3) {
nos[i] = scanner.nextInt()
}
println("Given values $nos")
Here, you can see i in 1..3 and you do not need to declare var i : Int = 1 as it'll be declared for you in the loop. Nor do you need the i = i+1 inside the loop for that matter.

SharePoint Microsoft.SharePoint.Client.CamlQuery recursively return folders only (including subfolders)

I am attempting to pull back all the Folders and SubFolders (there can be any number) from a SharePoint site. I don't want the files (there could be thousands), so I am basically trying to just build a folder hierarchy. Additionally I only want the User created folders and the main "Documents" folders, not all the system ones.
That said, I found the following example that I though should have worked, but when I reduce it to just the folders I only get the top level folders:
https://stackoverflow.com/questions/16652288/sharepoint-client-get-all-folders-recursively
Here is the state of the current code. I am probably just missing something on the load (like an expresssion?):
public static void LoadContent(Microsoft.SharePoint.Client.Web web, out Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.Folder>> listsFolders)
{
listsFolders = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.Folder>>();
var listsItems = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Where(l => l.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
var items = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllFoldersQuery());
ctx.Load(items);
listsItems[list.Title] = items;
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == Microsoft.SharePoint.Client.FileSystemObjectType.Folder).Select(i => i.Folder);
}
}
UPDATE
Just to help out anyone else who might just want the main folders and subfolders as a list of urls, here is the final code. I suspect it could be simplified but it is working. The trick after the help below was to get the "root" folder paths, which required a separate query. I think that is where it could prove easier to just get Folders -> Subfolders, but I have Folders -> Subfolders -> Subfolders and this solution gets that last subfolder, along with the root folders.
public static void LoadContent(Microsoft.SharePoint.Client.Web web, List<String> foldersList)
{
Dictionary<string, IEnumerable<Folder>> listsFolders = new Dictionary<string, IEnumerable<Folder>>();
var listsItems = new Dictionary<string, IEnumerable<ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Include(l => l.Title).Where(l => l.BaseType == BaseType.DocumentLibrary && !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();
}
foreach (var list in lists)
{
if (list.Title != "Form Templates" && list.Title != "MicroFeed" && list.Title != "Site Assets" && list.Title != "Site Pages")
{
foldersList.Add(list.RootFolder.ServerRelativeUrl);
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
listsItems[list.Title] = items;
}
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == FileSystemObjectType.Folder).Select(i => i.Folder);
}
foreach (var item in listsFolders)
{
IEnumerable<Folder> folders = item.Value;
foreach (Folder folder in folders)
{
foldersList.Add(folder.ServerRelativeUrl);
}
}
}
An example of what this returns:
1) In the provided example, to return Folder object, it needs to be explicitly included otherwise the exception occur, so replace the line:
ctx.Load(items);
with:
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
2) "system" libraries could be excluded like this:
var lists = ctx.LoadQuery(web.Lists.Where(l => !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
Modified example
public static void LoadContent(Web web, out Dictionary<string, IEnumerable<Folder>> listsFolders)
{
listsFolders = new Dictionary<string, IEnumerable<Folder>>();
var listsItems = new Dictionary<string, IEnumerable<ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Include(l =>l.Title).Where(l => l.BaseType == BaseType.DocumentLibrary && !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
listsItems[list.Title] = items;
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == FileSystemObjectType.Folder).Select(i => i.Folder);
}
}
Try this.
var lists = ctx.LoadQuery(ctx.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
Console.WriteLine(list.Title);
ListItemCollection listitems = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(listitems, items => items.Include(item => item.Id,item=>item.Folder));
ctx.ExecuteQuery();
foreach (var item in listitems)
{
Console.WriteLine(item.Folder.ServerRelativeUrl);
}
}

Parallel class in C#

i am copying one object to another using for loop which is dependent on noOFResults. I replaced Foreach loop by Parallel.For to increase the performance but the same cause major performance degrade. So I want to understand what is the cause of this ??
int resultCount = 0;
var apiSearchResults = new PS_HotelSearchResult[results.Count];
foreach (BE_HotelSearchResult result in results)
{
apiSearchResults[resultCount] = new PS_HotelSearchResult();
#region Fields of First Search
apiSearchResults[resultCount].RateType = (PS_RateType)result.RateType;
apiSearchResults[resultCount].HotelCode = result.HotelCode;
apiSearchResults[resultCount].Discount = result.AmountBeforeDiscountInSupplierCurr -
result.AmountAfterTaxInSupplierCurr;
apiSearchResults[resultCount].AmountAfterTax = result.AmountAfterTaxInSupplierCurr;
apiSearchResults[resultCount].AmountBeforeTax = result.AmountBeforeTaxInSupplierCurr;
apiSearchResults[resultCount].Currency = result.CurrencySupplier;
apiSearchResults[resultCount].IsUniversalApiResult = true;
if (result.Price != null)
{
apiSearchResults[resultCount].TotalGP = result.Price.TotalGP;
}
#endregion
#region Fields for Room
if (!Equals(result.RoomDetails, null))
{
int roomCount = 0;
apiSearchResults[resultCount].RoomDetails =
new PS_HotelRoomsDetails[result.RoomDetails.Length];
foreach (BE_HotelRoomsDetails roomDetail in result.RoomDetails)
{
if (roomDetail.CancellationPolicies == null)
{
throw new BusinessServiceException("HotelPrice.GetPrice - CancellationPolicies SHOULD NOT BE Null for rooms");
}
apiSearchResults[resultCount].RoomDetails[roomCount] = new PS_HotelRoomsDetails
{
SequenceNo = roomDetail.SequenceNo,
#region ExtraGuestCharge and ChildCharges
// Multiplied by number of nights becuase its a day wise price and we are setting it roomwise
SellExtraGuestCharges = roomDetail.SellExtraGuestCharges,
PubExtraGuestCharges = roomDetail.PubExtraGuestCharges,
ChildCharges = roomDetail.ChildCharges,
SellChildCharges = roomDetail.SellChildCharges,
#endregion
#region Discount and Tax
Discount = roomDetail.Discount,
TotalTax = roomDetail.TotalTax,
#endregion
};
int k = 0;
#region DayWiseRate
if (!Equals(roomDetail.Rates, null))
{
apiSearchResults[resultCount].RoomDetails[roomCount].Rates =
new PS_RoomRates[roomDetail.Rates.Length];
foreach (BE_RoomRates rate in roomDetail.Rates)
{
apiSearchResults[resultCount].RoomDetails[roomCount].Rates[k] = new PS_RoomRates
{
Amount = rate.Amount,
//Pricing is wrong
//SellingFare = rate.SellingFare
};
k++;
}
}
#endregion
k = 0;
#region Additional Charges
if (!Equals(roomDetail.AdditionalCharges, null))
{
apiSearchResults[resultCount].RoomDetails[roomCount].AdditionalCharges =
new PS_AdditionalCharges[roomDetail.AdditionalCharges.Count];
foreach (
BE_AdditionalCharges additionalCharge in
roomDetail.AdditionalCharges)
{
apiSearchResults[resultCount].RoomDetails[roomCount].AdditionalCharges[k] = new PS_AdditionalCharges
{
Charge = additionalCharge.Charge,
IncludedInTotal = additionalCharge.IncludedInTotal
};
k++;
}
}
#endregion
#region Price and Price Component
apiSearchResults[resultCount].RoomDetails[roomCount].Price = new HotelPriceAccounts();
if (!Equals(roomDetail.Price, null))
{
apiSearchResults[resultCount].RoomDetails[roomCount].Price.Discount = roomDetail.Price.Discount;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.PublishedFare = roomDetail.Price.PublishedFare;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.Tax = roomDetail.Price.Tax;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.OtherCharge = roomDetail.Price.OtherCharges;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.TotalGP = roomDetail.Price.TotalGP;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.IsGPEnabled = roomDetail.Price.IsGPEnabled;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.AgentMarkUpType =
(AgentMarkUpType)roomDetail.Price.AgentMarkUpType;
apiSearchResults[resultCount].RoomDetails[roomCount].Price.PriceId = roomDetail.Price.PriceId;
}
#endregion
roomCount++;
}
}
There are no for loops in the code, just foreach loops.
Do not expect loops to be automatically faster when using Parallel.For.
Especially when iterations have effect on the outer scope, the iterations can hardly be run in parallel. So all you are adding is overhead to split the iterations across tasks.
The outer scope is affected by changing Amount. k and apiSearchResults inside of the loops, just to name a few.

Resources