Jul 17, 2018

Common Collection Methods in Javascript and C#

Transform each element of collection into a new form and return new array 
javascript  
[1, 2, 3].map(x => x * 2);
c#
(new int[] {1, 2, 3}).Select(x => x * 2)

var students1 = new[] {
 new { Id = 1, FirstName = "John", LastName = "Singh", Addresss=new []{ new {City = "Boston" }, new { City = "Quincy" } } } ,
 new { Id = 2, FirstName = "Json", LastName = "Jha", Addresss=new []{ new {City = "Cambridge" } } }
 };
foreach ( var item in students1.SelectMany(y=>y.Addresss,(a,b)=> new { a, b} ) ) {
 Console.WriteLine($"{item.a.FirstName}-{item.b.City}");
}
Filters collection 
javascript
[1, 2, 3].filter(x => x > 2)
c#  
(new int[] {1, 2, 3}).Where(x=>x>1)
Accumulator function over a collection 
javascript  
[1, 2, 3].reduce((accumulate, currentValue, index) => accumulate + currentValue, 10)
c#
(new int[] {1, 2, 3}).Aggregate(10, (accumulate, currentValue) => accumulate + currentValue)
Determines whether a collection contains any elements which pass the test 
javascript
[1, 2, 3].some(x=>x>2) //true
[1, 2, 3].some(x=>x>3) //false 
c#
(new int[] {1, 2, 3}).Any(x=>x>2) 
Determines whether all elements of collection pass the test 
javascript
[1, 2, 3].every(x=>x>0) //true
[1, 2, 3].some(x=>x>1) //false 
c#   

(new int[] {1, 2, 3}).Any(x=>x>2) 
(new int[] {1, 2, 3}).All(x=>x>2)
Find first element of collection that pass the test 
javascript  
[1, 2, 3].find(x=>x>1) //2
[1, 2, 3].find(x=>x>7) //undefined
[1, 2, 3].findIndex(x=>x>0) //0
[1, 2, 3].findIndex(x=>x>7) //-1
c#  
(new int[] {1, 2, 3}).First(x=>x>1) //2
(new int[] {1, 2, 3}).First(x=>x > 7) //InvalidOperationException 
(new int[] {1, 2, 3}).FirstOrDefault(x=>x3) //0

(new int[] { 1, 2, 3 }).ToList().Find( x => x > 0 ) //0
(new int[] { 1, 2, 3 }).ToList().Find( x => x > 7 ) //0
(new int[] { 1, 2, 3 }).ToList().FindIndex( x => x > 7 ) // -1
Concatenates two Collections 
javascript
[1, 2, 3].concat([4, 5, 6])
[...[1, 2, 3],...[4, 5, 6]]
c#
(new int[] {1, 2, 3}).Concat(new int[] {4, 5, 6})
GroupBy 
javascript
[{name:'John', city:'Quincy'},{name:'Sam', city:'Boston'} ,{name:'Json', city:'Boston'}]
  .reduce((a,c,i)=>{
    let element = a.find(x=>x.key === c.city);
    element ? element.item.push({name:c.name}): a.push({key:c.city, item:[{name:c.name}]});
    return a;
  }, [])  
c#
var students = new[] { new { Id=1, FirstName = "John", LastName = "Singh" }, new { Id = 2, FirstName = "Json", LastName="Jha"} };
var address = new[] { new {StudentID =1, City = "Boston" }, new { StudentID = 1, City = "Quincy" }, new { StudentID = 2, City = "Quincy" } };
var query1 = students.
 Join( address, s => new { s.Id }, a => new { Id = a.StudentID }, ( s, a ) => { return new { Name = s.LastName + "," + s.FirstName, a.City }; } ).
 GroupBy( x => x.Name );
foreach ( var item in query1 ) {
 Console.WriteLine($"{item.Key}-{item.Count()}");
}
Sorting 
javascript  
console.log([{name:'John', age:42},{name:'Sam', age:25}].sort((x,y)=>x.age-y.age))
c#  
var a = new int[] { 1, 2, 3, 5 };
a.OrderBy(x=>x) //here x should implement ICampare
Slicing 
javascript
var number = [ 1, 2, 3];  
console.log(number.slice(0,2,))//1,2 (will not include end index), number object is not modified
console.log(number.splice(1,2,4)) //[2,3] starting from index 1 take out two and add 4 at the end  
console.log(number) //1,4

number = [ 1, 2, 3];  
console.log(number.shift());//1
console.log(number) //2,3
number = [ 1, 2, 3];  
console.log(number.pop());//3
console.log(number) //1,2

c#
var a = new int[] { 1, 2, 3, 5 };
a.Skip( 1 ).Take(2); //[2,3]
a.Take(1).Concat(a.Skip(3)) //[1,5]
a.Take(1).Concat(new int[]{4}).Concat(a.Skip(3)) //[1,4,5]
var b = new List<int>(){ 1, 2, 3, 5 };
b.RemoveAt(2);//remove 2nd item
b.Remove(5);//remove item with value as 5

Add New Item
javascript
[1,2,3].push(4)// add 2 to end
[1,2,3].upshift(0)//add 0 to starting

c#
stIndex(x=>x=
(new List<int>(){1,2,3,2,5}).Add(6) (new List<int>(){1,2,3,2,5}).Insert(0,0)
Index Of Item 
javascript
[1,2,3,1].indexOf(1,2)///eturn 3
c#
Array.IndexOf( [1,2,3,1], 1, 2 ) //return 3
(new List<int>(){1,2,3,2,5}).FindIndex(x=>x==2);
(new List<int>(){1,2,3,2,5}).FindLastIndex(x=>x==2);


String to Character Array 
javascript  
'this is string'.split('');
'this is string'.split('').join('');
c# 
"this is string".ToCharArray();
new String("this is string".ToCharArray());
String Split 
javascript  
'this is string'.split('is');
c# 
"this is string".Split(new char[]{'i', 't'}, StringSplitOptions.RemoveEmptyEntries);
"this is string".Split(new string[]{is, str},StringSplitOptions.RemoveEmptyEntries );
Substring 
javascript  
'abcdef'.substring('0,3');//abc start index and end index not include end index
c#
"abcd".Substring(1,2);bd//start index and length

Join Collection of String
javascript  
'this is string'.split(' ').join(',');
c# 
string.Join(",","this is string".Split(" "))
https://javascript.info/string

No comments:

Post a Comment