Is there an equivalent of bulk contains? - c#

Is there some utility to check whether a sequence contains multiple elements instead of using Contains repeatedly?
List<string> containter = new List<string>();
for (int i = 0; i < 10; i++)
{
containter.Add("string #" + i);
}
if (containter.Contains("string #2") && //Is it possible to replace this with one call passing two strings to improve efficiency
containter.Contains("string #6"))
{
//Do Something
}

According to the updated question, I've modified my answer:
List<string> containter = new List<string>();
for (int i = 0; i < 10; i++)
{
containter.Add("string #" + i);
}
//define a checklist
List<string> checkList = new List<string> { "string #2", "string #6" };
//we're in, if every item in checkList is present in container
if (!checkList.Except(containter).Any())
{
Console.WriteLine("true");
}
Still you may use Any. But in this context it would be nice to use Except method.
If every item in checkList is present in the container the resulting sequence would contain no elements, so Any should return false.

I am assuming you want to compare two sequences, and want to know if one sequence contains all of the elements in another sequence.
var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
bool outerContainsAllInnerElements = inner.TrueForAll(i => outer.Contains(i));
Alternatively, you could use Intersect(), but that will project your items into a new sequence when you attempt to get its count. If that's what you want, great, but if you don't need to know which elements intersect, then TrueForAll() would save that overhead.
var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
var elementsInBoth = outer.Intersect(inner);
bool outerContainsAllInnerElements = (elementsInBoth.Count() == inner.Count());

Any:
string s = "I am a string";
string[] check = { "is", "my" };
Console.WriteLine(check.Any(x => s.Contains(x))); // False
s = "This is a string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True
s = "my string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True

Related

Searching for words in a string and comparing them

I can't come up with a word search code that would still output the word when the position of the word changes
class Program
{
static void Main(string[] arg)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
Console.InputEncoding = System.Text.Encoding.Unicode;
var srd = new MultiSet<Garders>()
{
new Garders("ірис, троянда, айстра, півонія, жоржин"),
new Garders("ірис, троянда, айстра, півонія, жоржин, хризантема, гладіолус"),
new Garders("ірис, троянда, айстра, півонія, гладіолус")
};
MultiSet<Garders>.Enumerator e = srd.GetEnumerator();
string[] temp = new string[3];
for (int i = 0; i < temp.Length; i++)
{
e.MoveNext();
temp[i] = e.Current.flower;
}
e.Reset();
while (e.MoveNext())
{
string[] srt = e.Current.flower.Split();
foreach (var item in srt)
{
if (temp[0].Contains(item) == temp[1].Contains(item)
&& temp[1].Contains(item) == temp[2].Contains(item))
Console.WriteLine(item);
}
Console.WriteLine();
}
}
}
}
My code only outputs the same words if they are in the same positions
You have written very complex logic, it should be very easy if you read the problem statement carefully.
Based on the discussion in a comment, you want to compare two collections whether they have the same items in the same order.
You could use List.
and compare like this.
List<string> ls1 = new List<string>() { "1", "2"};
List<string> ls2 = new List<string>() { "1", "2" };
bool isEqual = ls1.SequenceEqual(ls2);

C# List not comparing with equals operator

I am comparing two lists in C#. Here is the basic code
List<string> expectedTabs = new List<string>() { "Batch", "Card Services", "ReportingXXXXX" };
List<string> actualTabs = new List<string>() { "Batch", "Card Services", "Reporting" };
string [] text = new string[actualTabs.Count];
int i = 0;
foreach (IWebElement element in actualTabs)
{
text[i++] = element;
Console.WriteLine("Tab Text : " + text[i - 1]);
}
for(int x = 0; x < actualTabs.Count; x++)
{
Assert.IsTrue(expectedTabs.Count == actualTabs.Count); //this gives equal count
Console.WriteLine(expectedTabs[x] + " :: " + actualTabs[x]);
expectedTabs[x].Equals(actualTabs[x]); //Gives wrong result here
Console.WriteLine(expectedTabs.GetType()); //returns type as collection.list
}
Now the equal should return false when comparing the last element [ReportingXXXXX and Reporting] in both the lists, but it just gives the result as equal. I am not sure if I need to use something else here.
reducing your code to what I think is the relevant bits...
var expectedTabs = new List<string>() { "Batch", "Card Services", "ReportingXXXXX" };
var actualTabs = new List<string>() { "Batch", "Card Services", "Reporting" };
for (var x = 0; x < actualTabs.Count; x++)
{
var equal = expectedTabs[x].Equals(actualTabs[x]); //Gives wrong result here
Console.WriteLine(equal);
}
This produces
True
True
False
Where are you seeing the wrong result?
Your code / comparison works fine.

StringArrays As A List<> Items -> How Prevent Changing All Items By Changing One Item(predefined string array)

please see these codes :
List<string[]> items_1 = new List<string[]>();
string[] item = new string[] { "item_id_for_sell", "item_title", "item_id_main", "item_amount", "item_del_id" };
items_1.Add(item);
item[0] = "1";
item[1] = "1";
item[2] = "1";
item[3] = "1";
item[4] = "1";
items_1.Add(item);
item[0] = "2";
item[1] = "2";
item[2] = "2";
item[3] = "2";
item[4] = "2";
items_1.Add(item);
i am so confused about this list.
why all string arrays inside that list have "2" value at last?
how can i prevent that list to update itself by updating item (string array)?
thanks in advance
You're adding a reference to the same array three times, so changing the contents of the array will indeed allow that change to be seen however you get at it. It's important that you understand that the list doesn't contain the array itself - it contains references. See my article about reference types and value types for more information.
You probably just want a new array each time:
List<string[]> items_1 = new List<string[]>();
string[] item = { "item_id_for_sell", "item_title",
"item_id_main", "item_amount", "item_del_id" };
items_1.Add(item);
item = new string[] { "1", "1", "1", "1", "1" };
items_1.Add(item);
item = new string[] { "2", "2", "2", "2", "2" };
items_1.Add(item);
However, I'd urge you to reconsider whether an array of strings is really the best format here. Why not create an Item class with properties Id, Title, Main, Amount and DelId (whatever that means)? Then you can create a List<Item> which will be much easier to work with.

C# Comparing two sorted lists and outputting to a file

I'm trying to compare a list of strings compiled together against a master list and print them out to a text file. The problem I'm having is the printable list remains empty. How do I populate the third list? And, is this a proper use of List<>, if not, what should I use?
Edit: Sorry about that, prior to this method running, textInput and textCompare read from two files and are populated with strings 7 characters in length: one pulled from a text file, the other from an excel sheet. I then remove any nulls, and attempt to compare the two lists with listA.intersects(listB). MSDN mentioned it need to be enumerated through for the intersects to work, which is why I put it in a foreach.
void Compare()
{
List<string> matches = new List<string>();
textInput.Sort();
textCompare.Sort();
progressBar.Maximum = textInput.Count;
int increment = 0;
for (int i = textCompare.Count - 1; i >= 0; i--)
{
if (textCompare[i] == null)
{
textCompare.RemoveAt(i);
}
}
foreach (string item in textInput)
{
matches = textInput.Intersect(textCompare).ToList();
increment++;
progressBar.Value = increment;
}
//A break point placed on the foreach reveals matches is empty.
foreach (object match in matches)
{
streamWriter.WriteLine(match);
}
doneLabel.Text = "Done!";
}
From the description in your comment this would do it:
var textOutput = textCompare.Where(s => !string.IsNullOrEmpty(s))
.Intersect(textInput)
.OrderBy(s => s);
File.WriteAllLines("outputfile.txt", textOutput);
Note that you can remove the .Where() condition provided you don't have empty strings in your masterlist "textInput" (very likely there aren't). Also, if order doesn't matter remove the .OrderBy(), you end up with this then:
var textOutput = textCompare.Intersect(textInput);
File.WriteAllLines("outputfile.txt", textOutput);
Not sure why you have this in the loop.
foreach (string item in textInput)
{
matches = textInput.Intersect(textCompare).ToList();
increment++;
progressBar.Value = increment;
}
you just need
matches = textInput.Intersect(textCompare).ToList();
if you try something like
List<string> matches = new List<string>();
List<string> textInput = new List<string>(new[] {"a", "b", "c"});
textInput.Sort();
List<string> textCompare = new List<string>(new[] { "b", "c", "d" }); ;
textCompare.Sort();
int increment = 0;
for (int i = textCompare.Count - 1; i >= 0; i--)
{
if (textCompare[i] == null)
{
textCompare.RemoveAt(i);
}
}
matches = textInput.Intersect(textCompare).ToList();
matches should have { "b , "c" }. so your problem might be somewhere else.
Consider something like this:
are the 2 sort calls even necessary?
use LINQ extension methods to remove the blank/nulls
void Compare()
{
textCompare.RemoveAll(x => string.IsNullOrEmpty(x));
List<string> matches= textInput.Intersect(textCompare).ToList();
matches.ForEach(x=> streamWriter.WriteLine(x));
doneLabel.Text = "Done!";
}

How to test if a list contains part of a string

I have a list of numbers and I have to check if multiple or single numbers of a string are within that list.
For example, suppose I have a list list = new List<int> { 2, 3, 4, 5, ... } with the string strSegment = "2,8". Trying list.Contains(strSegment) clearly doesn't work. Is there any way I can do this without separating the strSegment?
This is the code I have so far:
List<string> matchedSegs = ...;
foreach (Common.Ticket tst in lstTST)
{
string segNums = tst.SegNums;
var result = segNums.Split(',');
foreach (string s in result)
{
if (matchedSegs.Contains(s))
{
blnHKFound = true;
break;
}
else
{
strSegsNotFound += tst.strAirSegNums;
blnHKFound = false;
}
}
}
Well, you can do it without splitting the strNumber, but you haven't really explained why you need that. I think splitting then using Intersect is the simplest approach and I'd recommend trying this first to see if it is good enough for you:
var result = strSegment.Split(',').Intersect(numbers);
Here's a more complete example:
string strSegment = "2,8";
List<string> numbers = new List<string> { "2", "3", "4", "5" };
var result = strSegment.Split(',').Intersect(numbers);
foreach (string number in result)
{
Console.WriteLine("Found: " + number);
}

Categories