GithubHelp home page GithubHelp logo

linq's Introduction

linq

This is a JavaScript implementation of the .NET LINQ library.

It contains all the original .NET methods plus a few additions.

Written in pure JavaScript with no dependencies.

Examples

// C# LINQ - delegate
Enumerable.Range(1, 10)
    .Where(delegate(int i) { return i % 3 == 0; })
    .Select(delegate(int i) { return i * 10; });

// linq.js - anonymous function
Enumerable.range(1, 10)
    .where(function(i) { return i % 3 == 0; })
    .select(function(i) { return i * 10; });
// C# LINQ - lambda
Enumerable.Range(1, 10).Where((i) => i % 3 == 0).Select((i) => i * 10);

// linq.js - arrow function
Enumerable.range(1, 10).where((i) => i % 3 == 0).select((i) => i * 10);
// C# LINQ - anonymous type
array.Select((val, i) => new { Value: val, Index: i }());

// linq.js - object literal
Enumerable.from(array).select((val, i) => ({ value: val, index: i }));

See sample/tutorial.js and the test folder for more examples.

Usage

Node.js (ES modules)

Install the latest version of the library with npm:

npm install linq

Load it in your code with the import syntax:

import Enumerable from 'linq'

let result = Enumerable.range(1, 10).where(i => i % 3 == 0).select(i => i * 10)
console.log(result.toArray()) // [ 30, 60, 90 ]

Because the library is an ES module, this code will only work if your project is also configured as an ES module. Add the following line in your package.json to make it an ES module:

"type": "module"

If you're not planning to use ES modules, check the CommonJS section below.

Node.js (CommonJS modules)

Install version 3 of this library:

npm install linq@3

Load it with the require syntax:

const Enumerable = require('linq')

let count = Enumerable.range(1, 10).count(i => i < 5)
console.log(count) // 4

The cjs branch contains the source code for the CommonJS version of the library.

TypeScript

Install the latest version of the library with npm.

Configure your compiler options in tsconfig.json

"compilerOptions": {
    "target": "ES2020",
    "moduleResolution": "node"
}

The library comes with a d.ts file containing type definitions for all the objects and methods, feel free to use them in your code:

import Enumerable from 'linq';

type tnum = Enumerable.IEnumerable<number>;
let x: tnum = Enumerable.from([1, 2, 3]);

Deno

Import the library from deno.land. Use the @deno-types annotation to load type definitions:

// @deno-types="https://deno.land/x/[email protected]/linq.d.ts"
import Enumerable from 'https://deno.land/x/[email protected]/linq.js'

let radius = Enumerable.toInfinity(1).where(r => r * r * Math.PI > 10000).first()

You can also install locally with npm. Use the full file path when importing the library:

// @deno-types="./node_modules/linq/linq.d.ts"
import Enumerable from './node_modules/linq/linq.js'

Browser

The minified version of the library is available in the release archive.

Load it via <script type="module">:

<script type="module" src="./linq.min.js"></script>
<script type="module">
    import Enumerable from './linq.min.js'
    Enumerable.from([1, 2, 3]).forEach(x => console.log(x))
</script>

You can also load the library via a CDN:

CDN URL
unpkg https://unpkg.com/linq/
jsDelivr https://jsdelivr.com/package/npm/linq
packd https://bundle.run/linq@latest?name=linq

Credits

Yoshifumi Kawai developed the original version of this library.

License

MIT License

linq's People

Contributors

304notmodified avatar cervengoc avatar ejuke avatar m0ns1gn0r avatar mastodon0 avatar mihaifm avatar miquik avatar neuroboy23 avatar noy-shimotsuki avatar scriby avatar smdern avatar styfle avatar tuan-tu-tran avatar ugaya40 avatar zastrowm avatar zhongchengyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linq's Issues

How do we work with the selected items

Hello, let's say I have the casual array:

var values = [1, 2, 3];

I want to select from that array and work with the results, right?

var selected = Enumerable.from(values).where(x => x%2 !== 0);
console.log("number of odd values: " + selected.length); // Expecting 2

However, what is returned from Where appears to be an Linq object wrapper of some sort.

How do I extract the actual values from the expression?

Otherwise, cannot give enough 👍 for this type of library package.

Thanks!

Publish latest to NPM

Hi @mihaifm,

Can you please publish master to npm?

I'm using linq in my TypeScript project with noImplicitAny enabled and currently the compiler errors on the typings for linq 3.0.7.

node_modules/linq/linq.d.ts(29,75): error TS7006: Parameter 'element' implicitly has an 'any' type.

node_modules/linq/linq.d.ts(37,5): error TS7010: 'constructor', which lacks return-type annotation, implicitly has an 'any' return type.

This is actually fixed in master but it hasn't been published to npm yet. Could you please publish to npm?

Thanks

Looking for maintainers

Hi everyone

I contacted the original author of this library and he mentioned that he is no longer maintaining it.
I initially created this repository to add his library to npm, but since then a small number of improvements have been added.
The code is stable, but it could use some enhancements like using the new ecmascript lambdas and all that good stuff.

Unfortunatelly I don't have the time to further maintain this as well, so if anyone wants to contribute let me know here.

thanks

Hi! Is this repo in npm??

Hi, I`am migrating from bower to npm, I looking for the same repository in npm, but I found severals with other tag version.

Is this repo in npm?
if yes, Why is the url?

Thanks for your help.

FirstOrDefault

FirstOrDefault doesn't appear to work.
Enumerable.from([]).firstOrDefault(15) // null

Select specific keys with their values.

How can I select a group of specific values with their keys?
I want to able to perform a query similar to "select id, name, ... from table"
meaning I want the result to be an array only containing the fields I chose.
Thanks

Using linq.js without Node? (ie. browser)

I am trying to use this library within a web application, and am having a hard time sorting out how to get Enumerable to be defined globally as the require() bit is a Node thing.

How can I go about doing this?

Why mention anything like IEnumerable or Enumerator?

Hello,

Just curious, this is an interesting JavaScript extension. But I wonder, why have anything to do with IEnumerable or Enumerator? Why not embrace the goodness of the JavaScript Array, but with LINQ feel to it?

For instance,

if (Array.prototype.any === undefined) {
    Array.prototype.any = function (match) {
        match = match || function (x) { return true; }
        for (let x in this) {
            if (match(x)) { return true; }
        }
        return false;
    }
}

Or, similarly for first:

if (Array.prototype.first === undefined) {
    Array.prototype.first = function (match) {
        match = match || function (x) { return true; }
        for (let x in this) {
            if (match(x)) { return x; }
        }
        return null;
    }
}

Of course, being careful to mesh nicely with the JavaScript API.

groupby compareSelector overload wrong typing

Current typing is

groupBy<TKey, TElement, TResult, TCompare>(
  keySelector: (element: T) => TKey,
  elementSelector: (element: T) => TElement,
  resultSelector: (key: TKey, element: IEnumerable<TElement>) => TResult,
  compareSelector: (element: T) => TCompare
): IEnumerable<TResult>;

But the compareSelector actually accepts parameter of type TKey, not T (which is more intuitive than T, BTW).
This probably happens because it is passed as a dictionary comparer inside of toLookup method, but I haven't investigated this further.

Are you accepting new features/fixes?

e.g. #20 for a bug/fix
I also wanted to add iterator support so I could use for..of directly instead of using toArray first.

I only ask as this is a copy of codeplex's version but with a few npm fixes, right?
This repo seems to be the most used with 5000 monthly installs, and I personally use it a lot (well, I use a 'fork' (not actually a fork in the git sense) with iterator support), so I'd like to pull some changes in

group by with sum producing wrong results

has someone else seen this. i have large amount of data on which i am doing group by operations..like (1500 rows of data) and when i do group by it does not produce the correct result. it adds the numeric column correctly but puts the amount in wrong key. i tried doing it and matching wit excel pivot table and my results are not tying. has anyone else seen it?

Version in bower.json does not correspond to released version

Version in bower.json needs to be bumped to 3.0.5

{
"name": "linqjs",
"version": "1.0.0", //Change to 3.0.5
"main": "linq.js",
"ignore": [
"*/.",
"extensions",
"test",
"_.md",
"CHANGELOG",
"package.json"
],
"homepage": "https://github.com/mihaifm/linq",
"_release": "6b76ff6f5f",
"_resolution": {
"type": "branch",
"branch": "master",
"commit": "6b76ff6f5f77d3a4f7a7812bb9a979536f7e5e78"
},
"_source": "git://github.com/mihaifm/linq.git",
"target": "",
"_originalSource": "linqjs",
"_direct": true
}

Broken with node v0.10.29

I cannot manage to convert an array to Enumerable.

Enumerable.from() keeps returning an empty object {}

This is the output I get from sample.js:

first step of Lambda Expression


Scope of lambda expression


from(Object) -> convert to keyvaluePair

foo:a
bar:100
foobar:true

forEach (continue and break)

1:foo
3:foo
5:foo

Grouping and ref/value comparen

false
false
------
------

Regular Expression matches

0 : abcd
1 : c
index : 0
input : abcdefgABzDefabgdg
toString() : abcd,c

---
0 : ABzD
1 : z
index : 7
input : abcdefgABzDefabgdg
toString() : ABzD,z

---
0 : abgd
1 : g
index : 13
input : abcdefgABzDefabgdg
toString() : abgd,g

---

LazyEvaluation and InfinityList

57

Dictionary

zzz
huga
a:zzz
b:huga

Nondeterministic Programs

Please also add a reference output and/or a unit test.

As you can see from this part:

Grouping and ref/value comparen

false
false
------
------

The Enumerable.from() is not working

ES6 Iterable

As a former C# developer I like your library. Just want to know, any plans to use ES6 Iterable instead of custom Enumerable? If you want to support old browsers, would it be possible to have Enumerables to use Iterables under the hood for modern browsers? Also relates to #51

Thanks

How to use.

Your example is in uppercase, but it is in lowercase when used. I feel that your example should be adjusted to lowercase.

For example, your example is (Enumerable.Range(1, 10).Where(delegate(int i) { return i % 3 == 0; }))

But I actually use (Enumerable.from(array).where("x=>x.name=='删除'").toArray();)
微信截图_20191206170242

Otherwise, report wrong.

about the package on NPM

The package on the NPM have some issues so please tell me that when will the latest package be released on the NPM?

can't find updated version on cdn; can't install linq from bower

I'm trying to find minified and not minified versions of linq that I can use in a browser. Ideally I could just grab this off of a cdn, but it seems like the latest (https://cdnjs.com/libraries/linq.js) is 2.2.0.2 and you're on version 3 now.

I couldn't find anything in the readme about using this in the browser, but I saw in another issue that "bower should work". I've never heard of bower, but I gave it a shot. When I run

$ bower install linq

I get

fatal: repository 'https://github.com/mihaifm/linq/blob/master/linq.js.git/' not found

Is there any way to easily use the latest version in my browser?

When using a string for the selector using TypeScript it doe snot compile. Please help I am not very familiar with TypeScript

Like doing this
Enumerable.from(dataVals).where("$.indexOf("" + parameterName + "") !== -1").singleOrDefault("", "$").replace(/+/g, " ").split("=")[1];

instead of doing
return Enumerable.from(dataVals).where(p=> p.indexOf(parameterName) !== -1).singleOrDefault().replace(/+/g, " ").split("=")[1];

for most cases I can rewrite but I have a few specific that it is easier to use the string selector

Thanks

Find Function

	Enumerable.prototype.find = function (compareSelector) {
        compareSelector = Utils.createLambda(compareSelector);
		
		var result = null;
		
		this.forEach(function(item) {
			if (compareSelector(item)) {
				result = item;
				return;
			}
		});
		
		return result;
    };

Usage:

var result = Enumerable.from(list).find("x => x.Id == " + somevariable.Id);

It works fine and I hope you like it. It could use some optimization of code quality though.
I don't like the "x => x.Id == " + somevariable.Id part, because the somevariable.Id is outside of the quotation marks. Maybe you got a better solution for this problem.

C# Equivalent would be:

        public static T Find<T>(this IList<T> source, Func<T, bool> condition)
        {
            foreach (var item in source)
            {
                if (condition(item))
                {
                    return item;
                }
            }
            return default(T);
        }

Usage:

var result = list.Find(x => x.Id == somevariable.Id);

firstOrDefault default value that equates to false yields null

If you call firstOrDefault with a default value that equates to false then the return value will be null if the enumerable is empty.

testing.firstOrDefault(null, 0) yields null
testing.firstOrDefault(null, false) yiels null

This is because line at 1869 defaultValue = defaultValue || null

shouldn't it be defaultValue = (typeof(defaultValue) === 'undefined') ? null : defaultValue

That way passing in null yields null, passing in an undefined value yields null everything else yields the supplied defaultValue when the enumerable is empty

Fix license

Currently LICENSE file states:

Copyright (c) < year > < copyright holders >

You should provide neuecc and yourself as copyright holders, otherwise I have a problem considering it a valid license. Also, in README please provide a link to this file, not opensource.org

Typescript does not work

i use typing and linq js ver 3.0.4-beta5
On TS, when i write codes, i have no issue, on client, when i launch on browser, i get this error:

angular.min.js:118 ReferenceError: Enumerable is not defined

and when i traced the linq.js file: it goes to the first if:
this one:

// module export
    if (typeof define === Types.Function && define.amd) { // AMD
        define("linqjs", [], function () { return Enumerable; });
    }

Would you fix it?

Bug: Doesn't allow defaultValue = undefined in firstOrDefault

Enumerable.prototype.firstOrDefault = function (predicate, defaultValue) {
        if (predicate) {
            if (typeof predicate === Types.Function || typeof Utils.createLambda(predicate) === Types.Function)
                return this.where(predicate).firstOrDefault(null, defaultValue);

                defaultValue = predicate;
        }

        defaultValue = defaultValue || null; // THIS LINE
        ...

Maybe we should remove this line from firstOrDefault to allow undefined as default value?

It is specially important because the user might pass in undefined explicitly for the parameter defaultValue (which is the conventional missing value in JS), and this undefined value will get overloaded with null.

Even the type definition doesnt indicate that the return type might be T or null. In fact, type definition doesn't allow passing in null explicitly as defaultValue (which would make things more explicit and understandable for users).

The user has no way of knowing this unless they actually look into the code.

question

can i add a new comparator in the query ?

Differences with docs?

I am not entirely sure where this should go, as really this is just a republish of the codeplex one, but given codeplex is pretty much dead I am not sure where to put it.

Anyway the docs on the side show SingleOrDefault(default, predicate) however the code in here is singleOrDefault(predicate, default).

So is there any sort of idea if this is now going to become the maintained build or should this be raised on codeplex?

orderBy not working with null values

We're getting some really weird behavior when using orderBy on arrays with null in them.

Below is a test case running linq 3.2.1 on node 10.15.3.

const Enumerable = require('linq');

const data = ['2019-10-01', null, '2019-09-12', '2019-09-15', null];
const result = Enumerable.from(data).orderBy(x => x).toArray();

result.forEach(x => console.log(x));

Expected output:

null
null
2019-09-12
2019-09-15
2019-10-01

Actual output:

2019-10-01
null
2019-09-12
2019-09-15
null

Thanks in advance for any help you can provide.

bower.json is incomplete

when using yeoman, it doesn't install linq.js as a vendor. This is only because the 'bower.json' file is missing 'main'... I solved it by changing it to this...

{
"name": "linqjs",
"homepage": "https://github.com/mihaifm/linq",
"_release": "6b76ff6f5f",
"_resolution": {
"type": "branch",
"branch": "master",
"commit": "6b76ff6f5f77d3a4f7a7812bb9a979536f7e5e78"
},
"_source": "git://github.com/mihaifm/linq.git",
"_target": "*",
"_originalSource": "linqjs",
"_direct": true,
"main": "./linq.js"
}

argument of .zip()

IEnumerable<T>.zip() accepts U[] (or IEnumerable<U>) as the first argument.

Enumerable.from([1, 2, 3])
    .zip(["a", "b", "c"], (first, second) => `${first}${second}`)
    .toArray();

// => ["1a", "2b", "3c"]

So, definitions should be like this:

zip<U, TResult>(second: IEnumerable<U>, resultSelector: (first: T, second: U, index: number) => TResult): IEnumerable<TResult>;
zip<U, TResult>(second: { length: number;[x: number]: U; }, resultSelector: (first: T, second: U, index: number) => TResult): IEnumerable<TResult>;
zip<U, TResult>(second: U[], resultSelector: (first: T, second: U, index: number) => TResult): IEnumerable<TResult>;

can't easily convert to javascript Map

Maybe I'm missing something here, but when you have an enumerable you can to toDictionary but you can't do toMap to create a regular javascript map. Very confused. I think ENikS/LINQ allows you to do that quite simply.

Incompatible with Webpack/Typescript/Angular

If I import it,

import 'linq';

I get intellisense, but it doesn't compile:

'Enumerable' refers to a UMD global, but the current file is a module. Consider adding an import instead.

Used with: Webpack, Angular 4, Typescript

GroupBy<Tkey> has wrong return type

Hi,

First, thanks for this, it's a really cool lib :-)

While I was using it, I noticed that in the typings, the return type for groupBy is odd:

linq/linq.d.ts

Line 121 in 27a8af6

groupBy<TKey>(keySelector: (element: T) => TKey): IEnumerable<IGrouping<TKey, any>>;

// truly, return type is IEnumerable<IGrouping<TKey, T>> but Visual Studio + TypeScript Compiler can't compile.
groupBy<TKey>(keySelector: (element: T) => TKey): IEnumerable<IGrouping<TKey, any>>;

Like the comment says, the true return type should be using T instead of any.
But I have the impression that the reason it invokes for not returning the right return type is moot.
I don't really know how this Visual Studio + TS compiler works but in the typescript project I'm working on, I just went and corrected it in my 'node_modules` folder directly and my editor started giving correct intellisense.

So I was wondering if you could just correct this.

If you want I can do a pull request.

Thanks!

C# Linq: assigning variables during join

The console returns unexpected "." on line 68 in linq.js if I use linq like this:

Enumerable.from(a).join(b, "l1 => l1.ArticleId", "l2 => l2.Id", "(l1, l2) => { l1.Article = l2; return l1; }").toArray();

To allow assigning variables during the join the line 68 in linq.js:

f = new Function(expr[1], "return " + expr[2]);

must be changed to this:

f = new Function(expr[1], (expr[2].includes("return") ? expr[2] : "return " + expr[2]));

The C# equivalent as follows:

a.Join(b,
l1 => l1.ArticleId, l2 => l2.Id, (l1, l2) =>
{
	l1.Article = l2;
	return l1;
}).ToArray();

Incorrect Enumerable type when object contains length property

Hello
I tried to use your library with objects with this structure:

const vehicle = {
    weight: 1000,
    length: 5,
    color: "Blue",
    ...
}

and wanted to filter some values using .where method

Enumerable.from(vehicle)
    .where(i => excludedFields.indexOf(i.Key) == -1)
    .toObject(i => i.Key, i => i.Value);

I expected that .from function would convert my object to KeyValuePair. Unfortunately this method considered that input is array and didn't convert object to KeyValue

I checked the source code and found this statement on the row 300

// array or array like object
if (typeof obj.length == Types.Number) {
    return new ArrayEnumerable(obj);
}

It looks like any object with length property will be converted to ArrayEnumerable independent of another properties.
Is it possible to check for Arrays by another way (something like instanceof call)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.