TypeScript vs. C#: LINQ

TypeScript vs. C#: LINQ

TypeScript 没有等效于 LINQ 的语言集成自然查询方面?不能在 TypeScript 中写入以下 LINQ 语句

1
var adultUserNames =  from in users  where u.Age >= 18  select u.Name;

但是,位于 LINQ 核心的 iE6<T>扩展方法在 TypeScript 中具有等效项(或可以模拟)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Aggregate
All
Any
Append
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
First
FirstOrDefault
List.ForEach
GroupBy
Intersect
Last
LastOrDefault
Max
Min
OfType
OrderBy / ThenBy
Reverse
select
SelectMany
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
Union
where
Zip

Aggregate

1
2
3
4
5
6
// C#
var leftToRight = users.Aggregate(initialValue, (a, u) => /* ... */);
  
// TypeScript
const leftToRight = users.reduce((a, u) => /* ... */, initialValue);
const rightToLeft = users.reduceRight((a, u) => /* ... */, initialValue);

All

1
2
3
4
5
// C#
var allReady = users.All(u => u.IsReady);
  
// TypeScrip
tconst allReady = users.every(u => u.isReady);

Any

1
2
3
4
5
// C#
var isDirty = users.Any(u => u.IsDirty);
  
// TypeScript
const isDirty = users.some(u => u.isDirty);

Append

1
2
3
4
5
// C#
var allUsers = users.Append(oneMoreUser);
  
// TypeScript
const allUsers = [ ...users, oneMoreUser ];

Average

1
2
3
4
5
6
7
8
// C#
var avgAge = users.Average(u => u.Age);
  
// TypeScript
if (users.length < 1) { 
throw new Error(‘source contains no elements‘);
}
const avgAge = users.reduce((a, u) => a + u.age, 0) / users.length;

Cast

1
2
3
4
5
6
7
8
// C#
var people = users.Cast<Person>();
  
// TypeScript
const people = users as Person[];
// Note: not semantically the same. The C# version throws an exception
// if any of the users can‘t be cast to type Person.
//注意:在语义上不同。C# 版本引发异常如果无法强制转换为键入 Person 的任何用户。 

Concat

1
2
3
4
5
// C#
var allUsers = users.Concat(moreUsers);
  
// TypeScript
const allUsers = [ ...users, ...moreUsers ];

Contains

1
2
3
4
5
// C#
var hasAdmin = users.Contains(admin);
  
// TypeScript
const hasAdmin = users.includes(admin); // Use a polyfill for IE support

Count

1
2
3
4
5
// C#
var n = users.Count();
  
// TypeScript
const n = users.length;

DefaultIfEmpty

1
2
3
4
5
// C#
var nonEmptyUsers = Enumerable.DefaultIfEmpty(users);
  
// TypeScript
const nonEmptyUsers = users.length ? users : [ null ]; 

Distinct

1
2
3
4
5
// C#
var uniqueNames = users.Select(u => u.Name).Distinct();
  
// TypeScript
const uniqueNames = Object.keys(users.map(u => u.name).reduce((un, u) => ({ ...un, n }),{}));

ElementAt

1
2
3
4
5
6
7
8
// C#
var nth = users.ElementAt(n);
  
// TypeScript
if (n < 0 || n > users.length) { 
throw new Error(‘Index was out of range‘);
}
const nth = users[n]; 

ElementAtOrDefault

1
2
3
4
5
// C#
var nth = users.ElementAtOrDefault(n);
  
// TypeScript
const nth = users[n];

Empty

1
2
3
4
5
6
7
8
// C#
var noUsers = IEnumerable.Empty<User>();//?.NET 4.0 没找到 找到的是DefaultIfEmpty
//
var noUsers = IEnumerable.DefaultIfEmpty<User>();
  
// TypeScript
const noUsers: User[] = [];
const noUsers = [] as User[];

Except

1
2
3
4
5
6
7
8
// C#
var maleUsers = users.Except(femaleUsers);
  
// TypeScript
const maleUsers = users.filter
(
u =>  !femaleUsers.includes(u) // Use a polyfill for IE support(Use a polyfill for IE support)
); 

First

1
2
3
4
5
6
7
8
// C#
var first = users.First();
  
// TypeScript
if (users.length < 1) { 
throw new Error(‘Sequence contains no elements‘);
}
const first = users[0];

FirstOrDefault

1
2
3
4
5
// C#
var first = users.FirstOrDefault();
  
// TypeScript
const first = users[0];

List.ForEach

1
2
3
4
5
// C#
users.ToList().ForEach(u => /* ... */);
  
// TypeScript
users.forEach(u => /* ... */);

GroupBy

1
2
3
4
5
6
7
8
9
// C#
var usersByCountry = users.GroupBy(u => u.Country);
  
// TypeScript
const usersByCountry = users.reduce((ubc, u) =>
({ 
...ubc, 
[u.country]: [ ...(ubc[u.country] || []), u ],}),
{});

Intersect

1
2
3
4
5
// C#
var targetUsers = usersWhoClicked.Intersect(usersBetween25And45);
  
// TypeScript
const targetUsers = usersWhoClicked.filter(u =>  usersBetween25And45.includes(u) // Use a polyfill for IE support);

Last

1
2
3
4
5
6
7
8
// C#
var last = users.Last();
  
// TypeScrip
tif (users.length < 1) { 
throw new Error(‘Sequence contains no elements‘);
}
const last = users[users.length - 1];

LastOrDefault

1
2
3
4
5
// C#
var last = users.LastOrDefault();
  
// TypeScript
const last = users[users.length - 1];

Max

1
2
3
4
5
6
7
8
// C#
var oldestAge = users.Max(u => u.Age);
  
// TypeScrip
tif (users.length < 1) { 
throw new Error(‘source contains no elements‘);
}
const oldestAge = users.reduce((oa, u) => Math.max(oa, u.age), 0);

Min

1
2
3
4
5
6
7
8
// C#
var youngestAge = users.Min(u => u.Age);
  
// TypeScript
if (users.length < 1) {  t
hrow new Error(‘source contains no elements‘);
}
const youngestAge = users.reduce((ya, u) => Math.min(ya, u.age), Number.MAX_VALUE);

OfType

1
2
3
4
5
// C#
var bots = users.OfType<Bot>();//根据类型刷新元素
  
// TypeScript
// No equivalent   无等效项

OrderBy / ThenBy

1
2
3
4
5
6
7
8
9
10
11
12
// C#
var sorted = users.OrderBy(u => u.Age).ThenBy(u => u.Name);
  
// TypeScript
const sorted = users.sort((a, b) => { 
const ageDiff = b.age - a.age; 
if (ageDiff)
  return ageDiff; 
return a.name.localeCompare(b.name);
// Use a polyfill for IE support
}
);

Reverse

1
2
3
4
5
// C#
var backwards = users.Reverse();
  
// TypeScript
const backwards = users.Reverse();// Caution: users is also reversed! 原数组也翻转了

Select

1
2
3
4
5
// C#
var names = users.Select(u => u.Name);
  
// TypeScript
const names = users.map(u => u.name);  

SelectMany

1
2
3
4
5
// C#
var phoneNumbers = users.SelectMany(u => u.PhoneNumbers);
  
// TypeScript
const phoneNumbers = users.reduce((pn, u) => [ ...pn, ...u.phoneNumbers ], []); 

Single

1
2
3
4
5
6
7
8
9
10
// C#
var user = users.Single();
  
// TypeScript
if (users.length > 1) { 
throw new Error(‘The input sequence contains more than one element‘);
}else if (!users.length) { 
throw new Error(‘The input sequence is empty‘);
}
const user = users[0];

SingleOrDefault

1
2
3
4
5
// C#
var user = users.Single();
  
// TypeScript
const user = users[0]; 

Skip

1
2
3
4
5
// C#
var otherUsers = users.Skip(n);
  
// TypeScript
const otherUsers = users.filter((u, i) => i >= n); 

SkipWhile

1
2
3
4
5
6
7
// C#
var otherUsers = users.SkipWhile(predicate);
  
// TypeScript
let i = 0;
while (i < users.length && predicate(users[i++]));
   const otherUsers = users.slice(i - 1); 

Sum

1
2
3
4
5
6
7
8
// C#
var totalYears = users.Sum(u => u.Age);
  
// TypeScript
if (users.length < 1) { 
throw new Error(‘source contains no elements‘);
}
const totalYears = users.reduce((ty, u) => ty + u, 0);

Take

1
2
3
4
5
// C#
var otherUsers = users.Take(n);
  
// TypeScript
const otherUsers = users.filter((u, i) => i < n);

TakeWhile

1
2
3
4
5
6
7
// C#
var otherUsers = users.TakeWhile(predicate);
  
// TypeScript
let i = 0;
while (i < users.length && predicate(users[i++]));
  const otherUsers = users.slice(0, i - 1); 

Union

1
2
3
4
5
6
// C#
var allUsers = someUser.Union(otherUsers);
  
// TypeScript
const allUsers = otherUsers.reduce((au, u) => 
 au.includes(u)  ? au    : [ ...au, u ]}), someUsers));// Use a polyfill for IE support

Where

1
2
3
4
5
// C#
var adults = users.Where(u => u.Age >= 18);
  
// TypeScript
const adults = users.filter(u => u.age >= 18); 

Zip

1
2
3
4
5
6
7
8
// C#
var matches = buyers.Zip(sellers, (b, s) => new { Buyer = b, Seller = s });
  
// TypeScript
const matches = []
;for (let i = 0; i < buyers.length && i < sellers.length; i++) { 
 matches.push({    buyer: buyers[i],    seller: sellers[i],  });
}

水平有限,请大家见谅,翻译的有误,请指出。谢谢

原文地址 https://decembersoft.com/posts/typescript-vs-csharp-linq/

相关推荐