Tuesday, November 20, 2018

Lambda LINQ Group by on Multiple columns

foreach (var blackbook in db.Table<BookRequest>().Where(x => x.WorkingListID == listId).GroupBy(x => new {  x.Title, x.Used, x.Bind, x.ISBN, x.Copyright, x.PublisherName}).Select(x => new { bTitle = x.Key.Title, bUsed = x.Key.Used, bBind = x.Key.Bind, bISBN = x.Key.ISBN, bCopyright = x.Key.Copyright, bPublisherName = x.Key.PublisherName}))
                    {
                        var title = blackbook.bTitle.Replace("\"", "\"\"").Replace("&", "").Replace("@", "");
                        if (String.IsNullOrEmpty(title)) title = "Unknown";
                        sb.AppendLine(string.Format("\"**BBS\", {0}, {1}, , ,\"{2}\", \"{3}\", {4},  \"{5}\"", blackbook.bUsed, blackbook.bBind, blackbook.bISBN, title, blackbook.bCopyright, blackbook.bPublisherName.Replace("\"", "\"\"").Replace("&", "").Replace("@", "")));
                    }

Wednesday, October 31, 2018

GetUniqueFilename Method to rename a file if it exits

 private static string GetUniqueFilename(string fullPath)
        {
            if (!Path.IsPathRooted(fullPath))
                fullPath = Path.GetFullPath(fullPath);

            if (File.Exists(fullPath))
            {
                string filename = System.IO.Path.GetFileName(fullPath);
                string path = fullPath.Substring(0, fullPath.Length - filename.Length);
                string filenameWOExt = System.IO.Path.GetFileNameWithoutExtension(fullPath);
                string ext = System.IO.Path.GetExtension(fullPath);
                int n = 1;

                do
                    fullPath = System.IO.Path.Combine(path, string.Format("{0} ({1}){2}", filenameWOExt, (Math.Min(System.Threading.Interlocked.Increment(ref n), n - 1)), ext));
                while (File.Exists(fullPath));
            }

            return fullPath;
        }