Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a List of List of Items in LINQ c#

Tags:

c#

linq

I am a bit new to LINQ, here is my problem.

  • I have a List of List of Items
  • I like to get the Items which are present in only one List (and if I could get the List in which they are without re-iterating through the "list of list" that would be great).

I am trying without success to use the Aggregate / Except / Group keywords in the Linq query but nothing close to a solution so far.

[EDIT] Could be for instance List<List<int>> and the condition that the value of the int is is not in the others lists.

To be honest if I tried with several foreach I succeed to find the value items but as I am trying to learn LINQ I would like to know what kind of query I should write to get the results

for instance

 1,2,6
 1,6
 3,5
 5,10
 3,10,6

will return 2 and the first list

like image 403
call me Steve Avatar asked May 08 '10 17:05

call me Steve


People also ask

How to query list of list in C#?

var uniques = listlist. SelectMany(l => l. Select(i => new {Item = i, Origin = l})) . GroupBy(i => i.

Can we use LINQ query in a list object?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API. In a basic sense, LINQ to Objects represents a new approach to collections.

How to query in LINQ?

In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).

How to write in query in LINQ C#?

This query returns two groups based on the first letter of the word. List<int> numbers = new() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variables can also be implicitly typed by using var // Query #1. IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2.


2 Answers

var query = from list in lists
            from value in list
            where lists.Where(l => l.Contains(value)).Any()
            select new { List = list, Value = value };
like image 64
Roger Johansson Avatar answered Sep 20 '22 15:09

Roger Johansson


This will get you the unique integers:

var ints = listOfLists.SelectMany(l => l);
var uniques = ints.Where(i => ints.Count(val => val == i) == 1);
like image 25
John Rasch Avatar answered Sep 21 '22 15:09

John Rasch