LINQ: choose a collection?

I am trying to use LINQ:

IEnumerable<String> debtors = (from expense in CurrentExpenses
                               where expense.WhoPaid == username
                               select expense.WhoOwes.AsEnumerable()).Distinct();

( usernameand WhoPaid- strings, WhoOwesis ICollection<String>)

What I want to do is get IEnumerableof, for everyone expensewhere usernamepaid, all the people who owe it. I am not sure how to do this. Here is the compiler error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<string>>' to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion exists (are you missing a cast?)

What is the correct syntax for this?

+3
source share
2 answers

The code you provided does not compile because you are trying to assign a sequence of a sequence of lines (each top-level sequence coming from a certain expense) to a link that expects a sequence of lines.

, , , ? , .

// implicitly IEnumerable<string>
var debtors = CurrentExpenses.Where(expense => expense.WhoPaid == username)
                             .Select(expense => expense.WhoOwes)
                             .SelectMany(debtors => debtors) // flatten sequence
                             .Distinct();

( SelectMany ).

, :

var debtors = (from expense in CurrentExpenses
               where expense.WhoPaid == username
               from debtor in expense.WhoOwes
               select debtor).Distinct();

, , :

// implicitly IEnumerable<Expense>
var expensesPaidByUser = CurrentExpenses.Where(expense => expense.WhoPaid == username);

, , Expense, , , ; , .

, , , :

// implictly IEnumerable<anonymousType>
var debtorsByExpense = CurrentExpenses.Where(expense => expense.WhoPaid == username)
                                      .Select(expense => new { Expense = expense, Debtors = expense.WhoOwes });
+8

:

var debtors = ...

IEnumerable<String> debtors = ...

LINQ . var , . var IDE, , .

+2

Source: https://habr.com/ru/post/1768851/


All Articles