Get repeated path comparing 2 paths using c# - file

I have 2 file-paths.
eg:
Path 1 C:\Users\Me\FileFolder\File1.info
Path 2 C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info
I want to create a method to extract the repeated path:
Result C:\Users\Me\FileFolder
Is there a method to do this? Or how it can be done?

It can be done using String.Split method and Enumerable.TakeWhile
var part1 = path1.Split(Path.DirectorySeparatorChar);
var part2 = path2.Split(Path.DirectorySeparatorChar);
var commonParts = part1.TakeWhile((x,idx) => idx < part2.Length && part2[idx] == x);
if (commonParts.Any())
{
var result = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
}
Fiddle

I assume you want to find all common folders, so the path that is shared from both, try this:
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string root1 = Path.GetPathRoot(path1);
string root2 = Path.GetPathRoot(path2);
if (root1.Equals(root2, StringComparison.InvariantCultureIgnoreCase))
{
string[] folders1 = path1.Split(Path.DirectorySeparatorChar);
string[] folders2 = path2.Split(Path.DirectorySeparatorChar);
var commonFolders = folders1.TakeWhile((dir, index) =>
folders2.Length > index &&
dir.Equals(folders2[index], StringComparison.InvariantCultureIgnoreCase));
string commonFolderPath = string.Format("{0}{1}"
, root1
, Path.Combine(commonFolders.Skip(1).ToArray())); // Skip(1) skips root
Console.Write(commonFolderPath);
}
Result: C:\Users\Me\FileFolder

Alternative way is to use Zip with TakeWhile (suggested by Selman22).
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = part1.Zip(part2, (p1, p2) => p1 == p2 ? p1 : null)
.TakeWhile(s => s != null)
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
Slightly changed example of Selman22.
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = Enumerable.Range(0, Math.Min(part1.Length, part2.Length))
.TakeWhile(i => part1[i] == part2[i])
.Select(i => part1[i])
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);

Related

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

How to sort array of custom objects by customised status value in swift 3?

lets say we have a custom class named orderFile and this class contains three properties.
class orderFile {
var name = String()
var id = Int()
var status = String()
}
a lot of them stored into an array
var aOrders : Array = []
var aOrder = orderFile()
aOrder.name = "Order 1"
aOrder.id = 101
aOrder.status = "closed"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "open"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "cancelled"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "confirmed"
aOrders.append(aOrder)
Question is: How will I sort them based on status according to open, confirm, close and cancelled?
You have to provide a value that will yield the appropriate ordering when compared in the sort function.
For example:
extension orderFile
{
var statusSortOrder: Int
{ return ["open","confirmed","closed","cancelled"].index(of: status) ?? 0 }
}
let sortedOrders = aOrders.sorted{$0.statusSortOrder < $1. statusSortOrder}
In your code you should make an array to store each aOrder with aOrders.append(aOrder) at each aOrder defination.
Then sort it with below code, refor this for more.
aOrders.sorted({ $0.status > $1.status })
The answer for swift 3 is as following
Ascending:
aOrders = aOrders.sorted(by:
{(first: orderFile, second: orderFile) -> Bool in
first.status > second.status
}
)
Descending:
aOrders = aOrders.sorted(by:
{(first: orderFile, second: orderFile) -> Bool in
first.status < second.status
}
)

Can I Get The Object Name in A Loop? - Swift 2

I've written this loop. But, I'm wondering if I can do without the name property and just reference the name of the object?
class Param {
var name = ""
var value = 0.0
var skip = -1
}
let depth = Param()
depth.name = "depth"
let tankPressure = Param()
tankPressure.name = "tankPressure"
let time = Param()
time.name = "time"
let tankCapacity = Param()
tankCapacity.name = "tankCapacity"
let litresPerMinute = Param()
litresPerMinute.name = "litresPerMinute"
let params = [depth, tankPressure, time, tankCapacity, litresPerMinute]
for param in params {
let outlet = "\(param.name)Outlet.text!"
print(outlet)
}

Yii - CDbCriteria unexpected results

I am doing what looks like a simple query basically doing a WHERE clause on the competition_id and the prize_type
$criteria = new CDbCriteria;
$criteria->select = 't.*, myuser.firstname, myuser.surname';
$criteria->join ='LEFT JOIN myuser ON myuser.user_id = t.user_id';
$criteria->condition = 't.competition_id = :competition_id';
$criteria->condition = 't.prize_type = :prize_type';
$criteria->params = array(":competition_id" => $competition_id);
$criteria->params = array(":prize_type" => "1");
$winners = CompetitionWinners::model()->findAll($criteria);
Can anyone suggest what is wrong with my code... I am expecting around 4 rows.. but get over 600?
I just want to do ...
WHERE competition_id = 123 AND prize_type = 1;
Is there a simple function to simply output the SQL query for this SINGLE CDbCriteria 'event'?
try this
$criteria = new CDbCriteria;
$criteria->select = 't.*, myuser.firstname, myuser.surname';
$criteria->join ='LEFT JOIN myuser ON myuser.user_id = t.user_id';
$criteria->condition = 't.competition_id = :competition_id AND t.prize_type = :prize_type';
$criteria->params = array(":competition_id" => $competition_id,":prize_type" => "1");
$winners = CompetitionWinners::model()->findAll($criteria);
Or you could use CDbCriteria::addCondition()
$criteria->addCondition('t.competition_id = :competition_id')
->addCondition('t.prize_type = :prize_type');

Search Multidimensional Array ActionScript 3

If I have two arrays like the example below, how can I search the first part of each node in the 'score' array with the values in the 'search' array and return the value that is the second part of each node in the 'score' array? Basically in this case I'd want to get 5 and 7.
var score:Array = new Array();
score[0] = ["cat", "3"];
score[1] = ["dog", "5"];
score[2] = ["fish", "0.5"];
score[3] = ["bird", "0.25"];
score[4] = ["horse", "10"];
score[5] = ["cow", "15"];
score[6] = ["iguana", "7"];
var search:Array = ["dog", "iguana"];
Try with this code (using Dictionary):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var score:Dictionary = new Dictionary();
private var search:Array = ["dog", "iguana"];
public function init():void{
score["cat"] = "3";
score["dog"] = "5";
score["fish"] = "0.5";
score["bird"] = "0.25";
score["horse"] = "10";
score["cow"] = "15";
score["iguana"] = "7";
var t1:String = score[search[1]];
var t2:String = score[search[0]];
Alert.show(t1 + ' ' + t2); //prints 5 7
}
]]>
</mx:Script>
</mx:Application>
Or you can do this too:
var t1:String = score["dog"];
var t2:String = score["iguana"];
Or without Dictionary:
<?xml version="1.0" encoding="utf-8"?>
public function init():void{
score[0] = ["cat","3"];
score[1] = ["dog","5"];
score[2] = ["fish","0.5"];
score[3] = ["bird","0.25"];
score[4] = ["horse","10"];
score[5] = ["cow","15"];
score[6] = ["iguana","7"];
for(var j:int = 0;j<search.length;j++){
for(var i:int = 0;i<score.length;i++){
var temp:Array = score[i] as Array;
if(temp[0] == search[j]){
Alert.show(temp[1]);
}
}
}
}
]]>
</mx:Script>
Also you have not used an appropriate way to declare arrays, I recommend using my method or changing the array declaration.

Resources