Find a if filename does not exist in array of variable names - c#

I have a list of zipped files that contains a ZipArchive and the zipped filename as a String. I also have a final list of filenames that I need to check with my List and if the files do not match with my final list of filenames they should be dumped from my zipped file list.
I under stand that may not be worded the best so let me try and explain with my code/pseudo code.
Here is my list:
List<ZipContents> importList = new List<ZipContents>();
Which has two parameters:
ZipArchive which is called ZipFile
String which is called FileName
filenames is the finale list of file names that I am trying to check my ZipContents list against.
Here is the start of what I am trying to do:
foreach (var import in importList)
{
var fn = import.FileName;
// do some kind of lookup to see if fn would be List<String> filenames
// If not in list dump from ZipContents
}
The commented out section is what I am unsure about doing. Would someone be able to help get me on the right track? Thanks!
EDIT 1
I know I did not say this originally but I think that LINQ would be the much cleaner route to take. I am just not positive how. I am assuming that using .RemoveAll(..) would be the way I would want to go?

Loop through importList in reverse and remove items when not found in filenames. Assuming you don't have too many items performance should be fine:
for (int i = importList.Count - 1; i >= 0; i--)
{
if (!filenames.Contains(importList[i].FileName))
{
importList.RemoveAt(i);
}
}
You can't remove items from the list using a foreach because it modifies the collection, but you can do it with the construct in my example.

You could do something like:
if (!filenames.Contains(fn)) {
importList.Remove(import);
}
Alternatively, I believe you could use Linq to simplify this logic into just one line.
Edit:
Yes, you can just create a new list of just the ones you want, like this:
var newImportList = importList.Where(il => filenames.Contains(il.FileName)).ToList();

You can do this in one line. Just use LINQ to re-establish your list:
var filenames = new List<string> {"file1", "file2"};
var zipcontents = new List<ZipContents>
{
new ZipContents {FileName = "file1"},
new ZipContents {FileName = "file2"},
new ZipContents {FileName = "file3"}
};
zipcontents = zipcontents.Where(z => filenames.Contains(z.FileName)).ToList();
//zipcontents contains only files that were in 'filenames'
Honestly, this is what LINQ was made for: querying data.

Related

C# Comparing if two lists have the same order of items (alphabetical)

I'm facing a huge problem with comparing two lists. I just made copy of my first list and I tried to sort it. The problem is, I want to compare my original list and sorted one to see if they have same alphabetical order. I hope I provided enough information for my problem.
Thanks in advance
public void VerifyDataPrijave(string username)
{
List<string> listaTekstova = new List<string>(); //initializing new, empty List
var kartice = Repo.Kartice.CreateAdapter<Unknown>(false).Find(".//div[class='_63fz removableItem _95l5']");
foreach (var kartica in kartice) {
var slika = kartica.Find(".//tag[tagname='img']")[0];
var ime = slika.Find("following-sibling::div")[0];
string text = ime.GetAttributeValue("InnerText").ToString(); //loop through profile cards and getting Names as InnerText in variable text
listaTekstova.Add(text); //adding those "texts" I just found to an empty list initialized before
List<string> novaListaTekstova = new List<string>(listaTekstova); //clone (copy) of the very first one list
novaListaTekstova.Sort(); //sorting that list alphabetically (I suppose, not sure)
}
}
You can use SequenceEqual to compare to IEnumerables. In your case you can do something like this once all sorting has been done:
var isEqual = novaListaTekstova.SequenceEqual(listaTekstova);

Show list from last file to first save

I want to reverse the result displayed in a Combobox.
The last saved file would appear first, currently it is the opposite. it appears with this code:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
foreach (string file in files)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
According to my research, the solution would be:
.OrderByDescending(p => p.CreationTime).ToArray();
added somewhere. But I don't know. Every attempt I've made has been unsuccessful.
Currently:
101-00.06.52.TXT
101-00.06.54.TXT
101-00.06.56.TXT
Desired outcome:
101-00.06.56.TXT
101-00.06.54.TXT
101-00.06.52.TXT
Does anyone know?
Instead of static method Directory.GetFiles() method, use GetFiles() method from DirectoryInfo class. Apply OrderByDescending() on it.
Directory.GetFiles():
Returns the names of files that meet specified
criteria
Vs
DirectoryInfo.GetFiles():
Returns a file list from the current directory.
Like,
DirectoryInfo di = new DirectoryInfo(#"C:\Test\"); //Get the Directory information
var allTxtFiles = di.GetFiles("*.txt") //Get all files based on search pattern
.OrderByDescending(p => p.CreationTime) //Sort by CreationTime
.Select(x => x.Name); //Select only name from FileInfo object
foreach (string file in allTxtFiles)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
I don't know the reason why you problem. But if you want to receive correct result is simple. First try this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
comboBox1.ItemsSource = files;
if the result is not correct. Use this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
files = files.Reverse();
comboBox1.ItemsSource = files;

c# remove everything in List collection after a particular index

I want to be able to remove all elements in a List<string> after a certain index
List<string> s_array= new List<string>();
s_array.Add("a");
s_array.Add("x");
s_array.Add("c");
s_array.Add("y");
s_array.Add("e");
s_array.Add("e");
s_array.RemoveAll(/* what goes here?*/);
What can i put in RemoveAll to achieve this? for example say i wanted to cut out everything from c onwards?
Not sure what all your parameters are, so it's hard to say what approach will be best.
Using RemoveAll(), you could do:
s_array.RemoveAll(x => s_array.IndexOf(x) > s_array.IndexOf("c"));
You could use the key words Take or Skip to help - Example:
var s_array = new List<string> {"a","x","c","y","e","e" };
var sorted = (from x in s_array orderby x select x);
var first3 = sorted.Take(3);
var last2 = sorted.Take(2).Skip(5);

Find within large list using Contains within Linq

I have two large excel files. I am able to get the rows of these excel files into a list using linqtoexcel. The issue is that I need to use a string from one object within the first list to find if it is part of or contained inside another string within an object of the second list. I was trying the following but the process is taking to long as each list is over 70,000 items.
I have tried using an Any statement but have not be able to pull results. If you have any ideas please share.
List<ExcelOne> exOne = new List<ExcelOne>();
List<ExcelTwo> exTwo = new List<ExcelTwo>();
I am able to build the first list and second list and can verify there are objects in the list. Here was my thought of how I would work through the lists to find matching. Note that once I have found the matching I want to create a new class and add it to a new list.
List<NewFormRow> rows = new List<NewFormRow>();
foreach (var item in exOne)
{
//I am going through each item in list one
foreach (var thing in exTwo)
{
//I now want to check if exTwo.importantRow has or
//contains any part of the string from item.id
if (thing.importantRow.Contains(item.id))
{
NewFormRow adding = new NewFormRow()
{
Idfound = item.id,
ImportantRow = thing.importantRow
};
rows.Add(adding);
Console.WriteLine("added one");
}
}
If you know a quicker way around this please share. Thank you.
It's hard to improve this substring approach. The question is if you have to do it here. Can't you do it where you have filled the lists? Then you don't need this additional step.
However, maybe you find this LINQ query more readable:
List<NewFormRow> rows = exOne
.SelectMany(x => exTwo
.Where(x2 => x2.importantRow.Contains(x.id))
.Select(x2 => new NewFormRow
{
Idfound = x.id,
ImportantRow = x2.importantRow
}))
.ToList();

How do find line in a List

I have a text file that I am reading each line of using sr.readline()
As I read that line, I want to search for it in a List that the line should have been added to previously, then add the line to a NEW (different) list. How do I do this?
List.Contains(string) will tell you if a list already contains an element.
So you will wanna do something like:
if (previousList.Contains(line)){
newList.Add(line);
}
You could loop through this logic:
public void DoWhatYouAreAskingFor(StreamReader sr, List<string> list)
{
string line = sr.ReadLine();
if (!list.Contains(line))
{
list.Add(line);
}
}
You could do something like this.
List<string> listOfStrings = new List<string>() { "foo", "baz", "blah"};
string fileName = #"C:\Temp\demo.txt";
var newlist = (from line in File.ReadAllLines(fileName)
join listItem in listOfStrings
on line equals listItem
select line).ToList();
Edit: as a note, my solution shortcircuits the use of the streamreader and trying to find elements in another list and rather uses LINQ to join the elements of an existing list of strings with the lines from a given input file.
List.Contains(input) is certainly fine, and if you have a lot of inputs to filter, you may want to consider converting the searchable list to a HashSet.

Categories

Resources