String Operation on list - c#-4.0

I have a list of integers say
var items = new[] { 1, 2, 3, 4 };
I would like to cast them to list of strings. The reason is i need the set to be appear like
{<- 1 -> , <-2-> ,<-3-> ,<-4-> }
Normally i create another list like
List<string> list = new List<string>();
foreach (int i in items)
{
list.Add("<-" + i + "->");
}
Is there any shortcut to achieve the same result?

You could use LINQ and more specifically a combination of the .Select() and .ToList() extension methods:
var items = new[] { 1, 2, 3, 4 };
List<string> list = items.Select(i => string.Format("<-{0}->", i)).ToList();
The .Select() extension method projects each integer element to the corresponding string representation and the .ToList() extension method casts the result to a List<string>.

Try
var lst = items.ToList().ConvertAll(x=>x.ToString()).Select(x=>"<-"+ x+"->");

Related

Unable to access a list of strings generated dynamically

I generated a list of strings dynamically.
/
/I declared a list of strings and generated it using the length of my product.
late final List<String> recovered;
//the length of the products is 3
recovered = List.generate(products.length, (index) => ""));
//I assigned the list generated to the onChanged method inside my TextField.
TextField(
onChanged: (value) {
recovered[index] =
value;
log("the value is $value");
setState(() {});
},
}),
I want to get each String generated and assigned to a map dynamically. Like this:
{"product": "Noodles", "recovered": "2"} //recovered is the string from the text field, the product is gotten from the list of products.
I can't use recovered[index] because it returns the string at the first index only. I can't do this recovered[1] because since the string is generated dynamically, I can't get each index.
I figured out a solution that works.
List<Map> mapList = []; //Create a list of map
var myproduct = {}; //a map that will take the product and the recovered.
Then assigned the myproduct to the list of map (mapList) inside the TextField.
TextField(
onChanged: (value) {
recovered[index] =
value;
myproduct = {
"product": products[index]['product'], "quantity_delivered": value
}; mapList.add(myproduct);
}),

Random string in AS3

I have recently worked on AS3 project with a module that works like this:
I have 50 strings and I am picking one randomly of them at a given time. When I am done with the picked one I choose another one of the 49 left again randomly and so on.
I managed to solve this problem using helper arrays, for cycles, mapping index numbers with the strings. Although every thing works just fine I found my code very messed and hard to understand.
Is there a much more easy and cleaner way to solve this problem in AS3?
Maybe there is a library for getting random string out of strings?
Something simple like this class:
public class StringList
{
private var _items:Array = [];
public function StringList(items:Array)
{
_items = items.slice();
}
public function get random():String
{
var index:int = Math.random() * _items.length;
return _items.splice(index, 1);
}
public function get remaining():int{ return _items.length; }
}
And its usage:
var list:StringList = new StringList(['a', 'b', 'c', 'd']);
while(list.remaining > 0)
{
trace(list.random);
}
I'm not sure what do you want to do with that procedure, but here's one proposal:
var stringArray:Array = new Array("string1", "string2", "string2"); //your array with strings
var xlen:uint = stringArray.length-1; //we get number of iterations
for (var x:int = xlen; x >= 0; x--){ //we iterate backwards
var randomKey:Number = Math.floor(Math.random()*stringArray.length); //gives you whole numbers from 0 to (number of items in array - 1)
stringArray.splice(randomKey,1); //remove item from array with randomKey index key
var str:String = stringArray[randomKey]; //output item into new string variable or do whatever
}

Get the list of item from list that contains other list

I have a list of string.
I want to get the list items that matches the other list.
i.e, if First List values contains the value from other string return all the values.
List<string> fileNameToMatch = new List<string> { "nsevar", "cat", "elm", "nse isin", "l6scripsv2eq" };
List<string> fileToMatch = new List<string> { "fevnsevarc", "gfcatgf","ratstts","mymatch"};
The second list contains the values the are present in first list.
So return all values.
The output should be "fevnsevarc" and "gfcatgf" in list.
Can we use some link to get the names from the fileToMatch which contain data from fileNameToMatch
This should do the trick:
var res = fileToMatch
.Where(f => fileNameToMatch.Any(fn => f.IndexOf(fn) >= 0))
.ToList();
This is nearly self-explanatory: you are looking for all files f in fileToMatch such that a file name fn exists in the fileNameToMatch where f is contained anywhere in fn as a substring.
EDIT : (in response to a comment) To get the fn along with f, add a Select, and use an anonymous type, like this:
var res = fileToMatch
.Where(f => fileNameToMatch.Any(fn => f.IndexOf(fn) >= 0))
.Select(f => new {
File = f
, Name = fileNameToMatch.First(fn => f.IndexOf(fn) >= 0)
})
.ToList();
foreach (var match in res) {
Console.WriteLine("{0} - {1}", match.File, match.Name);
}
This should work:
var result = fileToMatch.Where(x => fileNameToMatch.Any(y => x.Contains(y)));

Convert paired lists into one-to-many lookup

I have lists (of equal length) of paired strings, call them "source" and "target". One source may map to multiple targets. Can I convert this to a lookup table (mapping a source to a list of targets) using LINQ? One (long-winded) way of doing this is:
// There may be multiple targets corresponding to each source
// as in the following example lists.
// NB. Lists are guaranteed same length
List<string> sourceNames = new List<string>() { "A", "B", "C", "A", "B", "C" };
List<string> targetNames = new List<string>() { "Z", "Y", "X", "W", "V", "U" };
// Use extension methods to make list of unique source names
List<string> uniqueSourceNames = sourceNames.Distinct().ToList<string>();
// For each unique source, make a list of the corresponding targets
Dictionary<string, List<string>> nameLookup = new Dictionary<string, List<string>>();
foreach (string sourceName in uniqueSourceNames)
{
List<string> targetsForSource = new List<string>();
for (int index = 0; index < sourceNames.Count; index++)
{
if (sourceNames[index] == sourceName)
targetsForSource.Add(targetNames[index]);
}
nameLookup.Add(sourceName, targetsForSource);
}
// Can now use the nameLookup dictionary to map a source name to a list of target names
// e.g. this returns "Z", "W"
List<string> targets = nameLookup["A"];
Is there a way to do this more efficiently using LINQ?
You can use GroupBy and ToDictionary:
var lookup = sourceNames
.Select((Source, i) => new { Target = targetNames.ElementAt(i), Source})
.GroupBy(x => x.Source)
.ToDictionary(g => g.Key, g => g.Select(x => x.Target));
Now every distinct source-string is mapped to an IEnumerable<string> targets.
foreach (var kv in lookup)
Console.WriteLine("{0} has destinations {1}"
, kv.Key
, string.Join(",", lookup[kv.Key]));
Edit: Here's the demo: http://ideone.com/b18H7X
You can use Zip and ToLookup:
var nameLookup = sourceNames
.Zip(targetNames, (x, y) => new { Source = x, Target = y })
.ToLookup(x => x.Source, x => x.Target);

c# string delimiter

I have string value like this:
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
I just need to retrieve role to string array. I wonder if there is the best way to split the string in C# 4.0
string[] arrStrRole = strRole.Split('|').Select .. ??
Basically, I need brandUK, brandUsa, brandAu to string[] arrStrRole.
Thanks.
string[] arrStrRole = strRole.Split('|').Select(r => r.Split(new []{"role="}, StringSplitOptions.None)[1]).ToArray()
results in an string array with three strings:
branduk
brankdusa
brandAu
you can use string[] arrStrRole = strRole.Split('|',','); and this will split according to | and , characters
You can use String.Split in this LINQ query:
var roles = from token in strRole.Split('|')
from part in token.Split(',')
where part.Split('=')[0] == "role"
select part.Split('=')[1];
Note that this is yet prone to error and requires the data always to have this format. I mention it because you've started with Split('|').Select.... You can also use nested loops.
If you need it as String[] you just need to call ToArray:
String[] result = roles.ToArray();
I would go with Regex rather than splitting string. In combination with your intended Select solution, it could look like this:
var roles = Regex.Matches(strRole, #"role=(\w+)")
.Cast<Match>()
.Select(x => x.Groups[1].Value).ToArray();
You could use an extension like this which would allow you to test it easily.
public static string[] ParseRolesIntoList(this string csvGiven)
{
var list = new List<string>();
if (csvGiven == null) return null;
var csv = csvGiven.Split(',');
foreach (var s in csv)
{
if (string.IsNullOrEmpty(s)) continue;
if(!s.StartsWith("role")) continue;
var upperBound = s.IndexOf("|");
if (upperBound <= 0) upperBound = s.Length;
var role = s.Substring(s.IndexOf("=") + 1,
upperBound - s.IndexOf("=") - 1);
list.Add(role);
}
return list.ToArray();
}
Test below found brankdusa typo in your example. Some of the other answers would not deal with brandAu as it matches slightly differently. Try running this test against them if you like
[Test]
public void Should_parse_into_roles()
{
//GIVEN
const string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
//WHEN
var roles = strRole.ParseRolesIntoList();
//THEN
Assert.That(roles.Length, Is.EqualTo(3));
Assert.That(roles[0], Is.EqualTo("branduk"));
Assert.That(roles[1], Is.EqualTo("brankdusa"));
Assert.That(roles[2], Is.EqualTo("brandAu"));
}
This gives an array of the 3 values.
void Main()
{
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
var arrStrRole = strRole.Split('|',',')
.Where(a => a.Split('=')[0] == "role")
.Select(b => b.Split('=')[1]);
arrStrRole.Dump();
}

Resources