How to get distinct values separately in string array? - c#

i have two string array
string[] oldname = ["arun","jack","tom"];
string[] newname = ["jack","hardy","arun"];
here i want compare these two string arrays to get these distinct values separately like :
oldname = ["tom"];
newname = ["hardy"];
how to achieve these ...

string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray();
string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray();

Let the two arrays were defined like the following:
string[] oldname = new[] { "arun", "jack", "tom" };
string[] newname = new string[] { "jack", "hardy", "arun" };
Then you can use the Extension method .Except to achieve the result that you are looking for. Consider the following code and the working example
var distinctInOld = oldname.Except(newname);
var distinctInNew = newname.Except(oldname);

Try this :
string[] oldname = new string[] { "arun", "jack", "tom" };
string[] newname = new string[] { "jack", "hardy", "arun" };
List<string> distinctoldname = new List<string>();
List<string> distinctnewname = new List<string>();
foreach (string txt in oldname)
{
if (Array.IndexOf(newname, txt) == -1)
distinctoldname.Add(txt);
}
foreach (string txt in newname)
{
if (Array.IndexOf(oldname, txt) == -1)
distinctnewname.Add(txt);
}
//here you can get both the arrays separately
Hope this help :)

string[] oldname = new []{"arun","jack","tom"};
string[] newname = new []{"jack","hardy","arun"};
// use linq to loop through through each list and return values not included in the other list.
var distinctOldName = oldname.Where(o => newname.All(n => n != o));
var distinctNewName = newname.Where(n => oldname.All(o => o != n));
distinctOldName.Dump(); // result is tom
distinctNewName.Dump(); // result is hardy

Related

foreach using split in C# and return Json result

IN MY CONTROLLER
var data1 = data.Split(',');
List opsi = new List();
foreach (string da1 in data1)
{
string[] data2 = da1.Split(':');
opsi.Add(data2[0]);
}
return Json(new
{
info = form["jml_soal"].ToString(),
data = opsi
});
Actual result : 1,2,3,4,5
Expected Result : B,C,D,A,D
Please Help!
You just need to change the opsi.Add(data2[0]) to opsi.Add(data2[1])
Attention to first and last character
string data = "[1:B,2:C,3:D,4:A,5:D]";
List<string> opsi = new List<string>();
//adding a substring to remove the first and last character [ and ]
var data1 = data.Substring(1, data.Length -2).Split(',');
foreach (string da1 in data1)
{
string[] data2 = da1.Split(':');
opsi.Add(data2[1]);
Console.WriteLine(data2[1]);
}
return Json(new
{
info = form["jml_soal"].ToString(),
data = opsi
});

ambiguity in String startswith the given string

I need to see if string starts with a given string but I am getting ambiguity, here is my code:
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
foreach (string s in arr)
{
if (input.StartsWith(s))
{
var rq= input.Replace(s, "");
}
}
If input is balance1234 , the if condition has to satisfy only with balance, but in my code it is satisfying with bal first.
Here is the solution (using the Hint given by Mr. Skeet):
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
string rq = input;
foreach (string s in arr.OrderByDescending(x => x.Length))
{
if (input.StartsWith(s))
{
rq = input.Replace(s, "");
break;
}
}

Newtonsoft.Json.Linq.JArray to string array C#

I have a JSON Array like
model.Users = ["Joe","Barny","Power","Tester"]
the model is dynamic
I want to convert model.Users to string[] Users
string[] Users = model.Users
How can I do that?
If model.Users is of type Newtonsoft.Json.Linq.JArray try to call:
string[] Users = model.Users.ToObject<string[]>()
string[] Users = new string[20];
int i = 0;
foreach ( string item in model.Users )
{
Users[i] = item;
i++;
}

Efficiently retrieving and filtering files by using filename

i am a newbie hier, i try to retreive files by using filenames, which have the following definition:
Items number + Revision + lot number.pdf
For example:
1109093-A2 (85806S).pdf
1109093-A3 (85806S).pdf
1109092-A1 (85806S).pdf
1109092-A2 (85806S).pdf
for this sample file: 1109093-A2 (85806S).pdf
Items number: 1109093
Revision: -A2
End item number: (85806S)
for my search result, i am supose to have only this files.
1109093-A3 (85806S).pdf
1109092-A2 (85806S).pdf
i must have only files, with the actual Revision like the one up there( A3 ,A2).
But it not, still now i am getting all Files, how can i sort it by Revision please???
A1, A2, A3, A.... (Revisions) represents the selection criteria I should use. I wrote the follow function for this job.
private string[] GetFiles()
{
strSourcePath = textBox1.Text;
strTargetPath = textBox2.Text;
string fileName = string.Empty;
strExtension = "*).pdf";
string[] files = null;
if (Directory.Exists(strSourcePath))
{
files = Directory.GetFiles(strSourcePath, strExtension, SearchOption.AllDirectories);
var Result = "";
string joined = String.Join("# ", Result);
files = null;
Result = joined.Split('#');
files = Result.Where(file => Regex.IsMatch(Path.GetFileName(file), "^[0-9]+")).ToArray();
}
else
{
MessageBox.Show("Source path does not exist!");
}
return files ;
}
After you got the paths, you can parse the filename, extract revision/etc and sort based on your criteria.
This code parse as an anonymous class (for readability) and sort based on ItemNumber, Revision.
The anonymous class contains the path and item number/revision/end number info.
See the demo for complete example
var paths = new [] {
"1109093-A2 (85806S).pdf",
"1109093-A3 (85806S).pdf",
"1109092-A1 (85806S).pdf",
"1109092-A2 (85806S).pdf",
};
var result = paths.Select(x => {
var match = Regex.Match(x, #"(?<ItemsNumber>\d+)-(?<Revision>\w+)\s+\((?<EndItemNumber>\w+)\).pdf");
if (match.Success)
{
return new { ItemNumber = match.Groups[1].Value, Revision = match.Groups[2].Value, EndItemNumber = match.Groups[3].Value, Path = x };
}
else {
return new { ItemNumber = "", Revision = "", EndItemNumber = "", Path = x };
}
})
.OrderBy(x => x.ItemNumber).ThenBy(x => x.Revision);
demo: https://dotnetfiddle.net/47uZni
Using your template I wrote this function, but the return value is always the same - one item, but not a list as I expected. I do not know why. Did you have some idea?
private string[] SortFileName(string []TemP)
{
var paths = GetTheFileName(TemP);
List<string> TheCollection = new List<string>();
var result = paths.Select(x => {
var match = Regex.Match(x, #"(?<ItemsNumber>\d+)-(?<Revision>\w+)\s+\((?<EndItemNumber>\w+)\).pdf");
if (match.Success)
{
return new { ItemNumber = match.Groups[1].Value, Revision = match.Groups[2].Value, EndItemNumber = match.Groups[3].Value, Path = x };
}
else {
return new { ItemNumber = "", Revision = "", EndItemNumber = "", Path = x };
}
})
.GroupBy(x => x.ItemNumber)
.Select(x => x.OrderByDescending(y => y.Revision).First());
foreach (var item in result)
{
TheCollection.Add(item.Path.ToString());
}
return TheCollection.ToArray();
}
PS: GetTheFileName(TemP); return an array with more than 130 items. thanks for the coming help.

How to compare and select values from string using Linq?

Had a class:
class filedate
{
public int id;
public string fname;
}
Fill my list with values:
List<filedate> List = ReadList(sqlFiles);
string[] FolderFiles = System.IO.Directory.GetFiles(path2Copy);
Trying to get results:
var results = List.Where(filedate =>
FolderFiles.Any(x=>Path.GetFileNameWithoutExtension(x) ==
Path.GetFileNameWithoutExtension(filedate.fname)));
I have the same files in List and FolderFiles, but get no results in results. I am a newbie to Linq. Where is the problem?
update:
List: (count) > 1000
for example:
<1023, 'tr_F2opervag_2808_1644.dat'>
FolderFiles example:
"\\domain.corp.dns\share\folder\tr_F2opervag_2808_1644.dat"
Update 2:
found out my mistake! Comment with intersection was helpful! This code is working:
var results = List.Where(
(filedate x) =>
{
return ! FolderFiles.Any(xxx =>
Path.GetFileNameWithoutExtension(xxx) ==
Path.GetFileNameWithoutExtension(x.fname));
});
You're code works fine for me so there's something wrong with the format of your data in the List coming back from the database.
Post an example of an fname value from the filedata object. It needs to be a valid fully qualified path.
This works fine for me.
public class FileData{
public int id;
public string fname;
}
void Main()
{
List<FileData> list = new List<FileData>{
new FileData { id=1, fname="C:\\install.res.1042.dll"},
new FileData { id=2, fname="C:\\install.res.1041.dll" },
new FileData { id=3, fname="C:\\install.res.9999.dll"}
};
string[] FolderFiles = System.IO.Directory.GetFiles("C:\\");
var results = list
.Where(fd =>
FolderFiles.Any(x=>Path.GetFileNameWithoutExtension(x) ==
Path.GetFileNameWithoutExtension(fd.fname)));
Console.WriteLine(results);
}
If you need to find the difference this should work. This is available via Enumerable.Except.
var dbFiles = ReadList(sqlFiles);
var dbFilePaths =
dbFiles.Select(fdate =>
Path.GetFileNameWithoutExtension(fdate.fname).ToLower());
var fsFilePaths =
Directory
.GetFiles(path2Copy)
.Select(filePath =>
Path.GetFileNameWithoutExtension(filePath).ToLower());
var diff =
dbFilePaths
.Except(fsFilePaths)
.Join(dbFiles,
filePath => filePath,
fdate => fdate.fname,
(filePath, fdate) => fdate)
.ToList();

Categories