I have 2 arrays
string[] allPossible = {"ID","Age","FirstName","LastName","Gender","Kudos"};
string[] enteredItems = {"Age", "LastName"};
I want to check the array enteredItems only contains elements found in the array
allPossible. I want to do this with LINQ.
I have looked
allPossible.Any(el => enteredItems .Contains(el));
and
allPossible.Intersect(enteredItems).Any();
Instead I loop thru the enteredItems and use Array.IndexOf(allPossible, x) == -1 return false.
The top data sample would return would return true...
however if only 1 element in the enteredItems array is not in the allPossible array then
there will be a false. ie.
string[] allPossible = {"ID","Age","FirstName","LastName","Gender","Kudos"};
string[] enteredItems = {"Age", "Geeky"};
would be false because 1 element in the 'enteredItems' array does not exist in the 'allPossible'
element.
There must be a LINQ query to do this.
Use Enumerable.Except
bool allInEntered = !enteredItems.Except(allPossible).Any();
Related
I have declared a two-dimensional object array as
object[,] sectionOpenings = new object[20, 4];
The first column is populated with string types, whilst the remaining three columns are all integers.
I wish to do a quick search to find a row with a matching string in the first column and have tried this
var first = Array.Find(sectionOpenings, p => p == "homedepot");
I get the following error:
Error CS0411 The type arguments for method 'Array.Find(T[], Predicate)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Any suggestions?
You can alter your code a bit to get what you what:
var first = Array.Find(sectionOpenings, p => p[0] == "homedepot");
this will look in each array row, the first column p[0] == "homedepot"
edit:
my bad, I thought about jagged arrays
Well its not a one liner, but you can create a method like so:
public static int GetMatchingRow(object[,] myArr, string findMe)
{
for (int i = 0; i < myArr.GetLength(0); i++)
{
if (myArr[i, 0] is string && myArr[i, 0] as string == findMe)
return i;
}
return -1;
}
I would suggest changing to a dictionary to ensure type safety- like so:
var sectionOpenings = new Dictionary<string, List<int>>();
sectionOpenings.TryGetValue("homedepot", out var result);
However, if you are stuck using a 2D array, you'll likely have to do this in two steps. One, you'll have to find the matching column. Two, you'll have to retrieve the column. Something like this could work:
object[,] sectionOpenings = new object[20, 4];
var firstRowMatch = Enumerable
.Range(0, sectionOpenings.GetLength(0)) // Gets row indices
.Where(row => sectionOpenings[row, 0].ToString().Equals("homedepot"))
.First();
var result = Enumerable
.Range(0, sectionOpenings.GetLength(1)) // Gets column indices
.Select(column => sectionOpenings[firstRowMatch, column])
.ToArray();
With this example, you will likely have to add some type checks and null checks to make sure that this doesn't explode with a NullReferenceException.
This is adapted from returning a whole column from a 2D array and getting the number of columns/rows from a 2D array on stack overflow.
PS. This assumes you're using System.Linq
I couldn't find this anywhere else.
I've an array of lists:
public List<xmldata>[] XMLArrayList = new List<xmldata>[9999];
To initialize and insert a list into each position, i do the following:
for(int m=0; m< XList.XMLArrayList.Count(); m++)
{
XList.XMLArrayList[m] = new List<xmldata>();
}
But i would like to count how many elements there aren't null.
EX: Positions 0 to 5 have a List on them. But other positions not.
Tried a linq approach:
int count = XList.XMLArrayList.Count(x => x != null);
But it returns me the array size (9999). How can i count the non null elements on an array of lists ?
Ps: Already tried Dictionary and And List of List - this approach works best for achieving what i need.
Thanks.
Try this:
int count = XList.XMLArrayList.Count(x => x.Count()>0);
you can also do this
XList.XMLArrayList.Where(x => x.Any()).Count();
I have an array:
List<String> TagArray = new List<string>(TagString.Split(','));
I want to remove certain elements, in the array; say - if the values contain the letter 'AAA'.
Is there a single line of statement in C# by which we can achieve the desired result?
Try this:
TagArray.RemoveAll(item => item.Contains("AAA"));
RemoveAll will remove all the items that would return true from the predicate you define. You can do this multiple time or you can || a bunch of contains together within one RemoveAll.
You could use LINQ here. For example
List<String> TagArray = TagString.Split(',')
.Where(tag => tab.IndexOf("AAA") < 0)
.ToList();
Remember to add System.Linq namespace.
Hope this helps !!
static void Main(string[] args)
{
string TagString = "WAAAA,APPLE";
List<String> TagArray = new List<string>(TagString.ToUpper().Split(',')).Where(x => !x.Contains("AAA")).ToList();
}
1 line and it works
List<String> TagArray = new List<string>(TagString.ToUpper().Split(',')).Where(x => !x.Contains("AAA")).ToList();
There is a method available in List<T> : RemoveAll(Predicate<T>)
var list = new List<string> {"AAABBBCCC", "AABBCC", "ABC", "CCAAACC"};
list.RemoveAll(s => s.Contains("AAA")); // Removes the first and the last element
RemoveAll() "iterates" over the list and provides you each element. The s represents an element from the list and the code after => is a condition. When the condition is true, the element is removed. The condition doesn't have to use the s variable, it can be arbitrary block that returns bool value.
So you can also write this:
list.RemoveAll(s =>
{
return a == 5;
});
I have the following string;
string[,] test=
{
{"0","0"},
{"0","0"},
{"0","0"},
{"0","1"},
{"5","0"},
};
I'd like to find a way to search the array for all lines that are unique.
So my desired output array would be.
string[,] output=
{
{"0","0"},
{"0","1"},
{"5","0"},
};
Does anyone have any simple ideas on how to achieve this?
you can do this with linq just call Distinct to select only unique values, like this
var query = (from arr in test
from value in arr
select value).Distinct();
or you can try the following method, This simply flattens the nested arrays into a sequence and calls Distinct to find the distinct elements. source this answer
var distinct = test.SelectMany(a => a).Distinct().ToArray();
An array is defined of assumed elements like I have array like String[] strArray = new String[50];.
Now from 50 elements only some elements are assigned and remaining are left null then I want the number of assigned elements.
Like here only 30 elements are assigned then I want that figure.
You can use Enumerable.Count:
string[] strArray = new string[50];
...
int result = strArray.Count(s => s != null);
This extension method iterates the array and counts the number of elements the specified predicate applies to.
Using LINQ you can try
int count = strArray.Count(x => x != null);
Use LINQ:
int i = (from s in strArray where !string.IsNullOrEmpty(s) select s).Count();