I have a comma separated string variable and i need to check its values exists in a given List
string freeServices = "1,7,13,21";
List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();
i have tried something like this
if (selectedServices.Contains(Convert.Int32(freeServices.Split(','))
{
}
can i do this? or is there any other easy way to find whether the free service ids in selected id list?
To check, all values are contained in SelectedServices:
string freeServices = "1,7,13,21";
var values = freeServices.Split(',').Select(o=>Convert.ToInt32(o)).ToList();
List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();
if (selectedServices.All(o=>values.Contains(o))
{
}
Try below query, you willget contains records
var containsValues = booking.SelectedServices.where(e=> freeServices.Split(',').Contains(e.ServiceID));
You could use All and int.Parse;
string freeServices = "1,7,13,21";
List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();
var splittedFreeServices = freeServices.Split(',').Select(k => int.Parse(k));
var result = selectedServices.All(x => splittedFreeServices.Contains(x));
if (result) //booking.SelectedServices contains all elements of freeServices as integer
{
}
Related
I have list of string
Like list1 contain 'pinky','smita','Rashmi','Srivani'
And string is like
String str = "pinky, Nandini'
I want to check if neither of str present in list1,proceed further.
how to do that?
If I understood correctly, you want to return false in the example case, so you can use Any method: Check if none of the elements of the list is already in the str, here is a one liner:
if (!list.Any(x=>str.Contains(x))) ....
You can use combination of .Any() with .Contains() with !,
var list1 = new List<string>(){ "pinky", "smita", "Rashmi", "Srivani" };
string str = "pinky, Nandini";
var list2 = str.Split(",");
var nameExists = list2.Any(x => list1.Contains(x));
if(!nameExists)
{
//Your code goes here.
}
As #Fildor said, you can use Intersect(). Elegant approach,
//All credit goes to #Fildor
var nameExists = list1.Intersect(list2).Any();
I have below comma separated string. This string contains relation which is needed in the application for processing.
string userInputColRela = "input1:Student_Name, input2:Student_Age";
Now, i need to extract Student_Name if i provide input as input1 and Student_Age if the input provided is input2.
How can i achieve this? I know i can go with looping but that will be a little lengthy solution, what is other way round?
You could parse the input string by splitting firstly on the comma, then again on the semi-colon to get the key-value pairs contained in it in dictionary form. For example:
string userInputColRela = "input1: Student_Name, input2: Student_Age";
var inputLookup = userInputColRela
.Split(',')
.Select(a => a.Split(':'))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim());
var studentName = inputLookup["input1"];
If your strings are always in the format input1:Student_Name, input2:Student_Age then probably you can use a Dictionary<k,v> and Split() function like
string userInputColRela = "input1:Student_Name, input2:Student_Age";
string input = "input1";
var args = userInputColRela.Split(',');
Dictionary<string, string> inputs = new Dictionary<string, string>();
foreach (var item in args)
{
var data = item.Split(':');
inputs.Add(data[0], data[1]);
}
Console.WriteLine(inputs[input]);
I am picking distinct values from a datatable column like below.
var uniqueCC = dtNew.AsEnumerable().Select(s => new { cc = s.Field<string>("ID"), }).Distinct().ToList();
var uniqueCode = dtNew.AsEnumerable().Select(s => new { Code = s.Field<string>("EAI"), }).Distinct().ToList();
Now I need to get the values alone in a comma seperated string and I'm using the below code and it doesn't take the value alone.
string strCC = String.Join(",", uniqueCC);
string strEAI = String.Join(",", uniqueCode);
Please provide some suggestions.
List values
cc=1, cc=2, cc=3
Expected Result
1,2,3
You can just use LINQ Select() method to pass the value alone to String.Join() :
string strCC = String.Join(",", uniqueCC.Select(o => o.cc));
Or just return string values instead of anonymous type in the first place :
var uniqueCC = dtNew.AsEnumerable().Select(s => s.Field<string>("ID")).Distinct();
string strCC = String.Join(",", uniqueCC);
You can use aggregate functions available in c#.
Let say you have a list of string called listOfString, then you can call the aggregate function like this.
string outString = listOfString.Aggregate((a, b) => a + "," + b);
It will do the trick.
As an extension to har07's excellent answer, if this is something you do a lot of the time, to save writing loads of code you could implement this as a static extension method, where you pass the datatype, the column name and your required separator - so it could handle different column datatypes and separators - in a separate file:
namespace Extensions
{
public static class LinqExtensions
{
public static String ReturnSeparatedString<T>(this DataTable datatable, string field, string separator)
{
var unique =
datatable.AsEnumerable()
.Select(s => new {cc = s.Field<string>(field),}).Distinct();
return String.Join(separator, unique.Select(o => o.cc));
}
}
}
Then call it from your code by creating a reference to your new Extensions.LinqExtensions class, and calling it directly on the dataTable like this:
var commaSeparatedIds = dataTable.ReturnSeparatedString<string>("ID",",");
var commaSeparatedEAIs = dataTable.ReturnSeparatedString<string>("EAI",",");
var commaSeparatedInts = dataTable.ReturnSeparatedString<int>("MYINTS",",");
var dotSeparatedStrings = dataTable.ReturnSeparatedString<int>("OtherId", ".");
I'm working on the Array in C#, as following code below, the uricontent is a List in which each string contains one JSON value, I could parse the content, however, I want to have one other array or List to store each parsed value, in the example below, rooms variable can store each time one JSON parsed value, now I wish to store those parsed values in one array.
int i = 0;
while (uricontent.Count != 0)
{
var rooms = JObject.Parse(uricontent[i].ToString())
["rooms"]
.Select(x => new
{
roomID = (string)x["room_name"],
Name = WebUtility.HtmlDecode((string)x["room_name"]),
Price = PriceHelper.Convert((string)x["discountedTotal"]),
Currency = (string)x["currency"],
Occupan = (int)x["adult"]
}).ToArray();
i++;
}
rooms {<>f_AnonymousType11[1]<>f_AnonymousType11[]
[0] { roomID = "Superior 1st floor", Name = "Superior 1st floor", Price = 207.4, Currency = "EUR", Occupan = 2 }
As indicating above, the rooms overwrite the data in each iteration, how can I store those values in one other array like
[1].....
[2].....
....
Thanks
I think what you need is the SelectMany method. SelectMany concatenates all of the IEnumerables generated by the inner Select statements, and returns them as a single IEnumerable, which can then be converted into an array:
var rooms = uricontent
.SelectMany(
uriContentElementJson =>
{
JObject uriContentElement = JObject.Parse(uriContentElementJson);
return uriContentElement["rooms"].Select(
room => new
{
RoomID = (string)room["room_name"],
Name = WebUtility.HtmlDecode((string)room["room_name"]),
Price = PriceHelper.Convert((string)room["discountedTotal"]),
Currency = (string)room["currency"],
Occupant = (int)room["adult"]
});
})
.ToArray();
I have an ArrayList that import records from a database.
Is there any method to check whether the arrayList contains schname that i want to match to another list which is an api?
List<PrimaryClass> primaryList = new List<PrimaryClass>(e.Result);
PrimaryClass sc = new PrimaryClass();
foreach (string item in str)
{
for (int a = 0; a <= e.Result.Count - 1; a++)
{
string schname = e.Result.ElementAt(a).PrimarySchool;
string tophonour = e.Result.ElementAt(a).TopHonour;
string cca = e.Result.ElementAt(a).Cca;
string topstudent = e.Result.ElementAt(a).TopStudent;
string topaggregate = e.Result.ElementAt(a).TopAggregate;
string topimage = e.Result.ElementAt(a).TopImage;
if (item.Contains(schname))
{
}
}
}
This is what I have come up with so far, kindly correct any errors that I might have committed. Thanks.
How about ArrayList.Contains?
Try this
foreach( string row in arrayList){
if(row.contains(searchString)){
//put your code here.
}
}
Okay, now you've shown that it's actually a List<T>, it should be easy with LINQ:
if (primaryList.Any(x => item.Contains(x.PrimarySchool))
Note that you should really consider using foreach instead of a for loop to iterate over a list, unless you definitely need the index... and if you're dealing with a list, using the indexer is simpler than calling ElementAt.
// check all types
var containsAnyMatch = arrayList.Cast<object>().Any(arg => arg.ToString() == searchText);
// check strings only
var containsStringMatch = arrayList.OfType<string>().Any(arg => arg == searchText);