var q = from t in dict
from v in t.Value.elements
select new { name = t.Key, element = v };
Enumerable.SelectMany. :
var q = dict.SelectMany(t => t.Value.elements.Select(v => new { name = t.Key, element = v }));
, t.Value.name , t.Key, .
, ?
-, , ; , , . , :
class NameElement
{
public string name { get; set; }
public string element { get; set; }
}
IEnumerable<NameElement> GetResults(Dictionary<string, MyStruct> dict)
{
foreach (KeyValuePair<string, MyStruct> t in dict)
foreach (string v in t.Value.elements)
yield return new NameElement { name = t.Key, element = v };
}
(, )?
( fooobar.com/questions/3208/..., , :)
, NameElement. , . :
var q = GetResults(dict);
:
var q = GetResults(dict, (string1, string2) => new { name = string1, element = string2 });
- (string1, string2) => new { name = string1, element = string2 } , 2 , (string1, string2), , , new { name = string1, element = string2 }.
:
IEnumerable<T> GetResults<T>(
IEnumerable<KeyValuePair<string, MyStruct>> pairs,
Func<string, string, T> resultSelector)
{
foreach (KeyValuePair<string, MyStruct> pair in pairs)
foreach (string e in pair.Value.elements)
yield return resultSelector.Invoke(t.Key, v);
}
T . , ( , #), , , : .
, T pair, T, v e, "element". , IEnumerable<KeyValuePair<string, MyStruct>>. , , . , dict pairs.
. foreach - T. ; Func<KeyValuePair<string, MyStruct>, T>. , , pair , Select resultSelector:
IEnumerable<T> GetResults<T>(
IEnumerable<KeyValuePair<string, MyStruct>> pairs,
Func<string, string, T> resultSelector)
{
foreach (KeyValuePair<string, MyStruct> pair in pairs)
foreach (T result in pair.Value.elements.Select(e => resultSelector.Invoke(pair.Key, e))
yield return result;
}
:
IEnumerable<T> GetResults<T>(
IEnumerable<KeyValuePair<string, MyStruct>> pairs,
Func<KeyValuePair<string, MyStruct>, IEnumerable<T>> resultSelector)
{
foreach (KeyValuePair<string, MyStruct> pair in pairs)
foreach (T result in resultSelector.Invoke(pair))
yield return result;
}
; , , , :
var q = GetResults(dict, pair => pair.Value.elements.Select(e => new { name = pair.Key, element = e }));
( ), KeyValuePair<string, MyStruct> TSource. :
T -> TResult
pairs -> sourceSequence
pair -> sourceElement
, , :
static IEnumerable<TResult> GetResults<TSource, TResult>(
this IEnumerable<TSource> sourceSequence,
Func<TSource, IEnumerable<TResult>> resultSelector)
{
foreach (TSource sourceElement in sourceSequence)
foreach (T result in resultSelector.Invoke(pair))
yield return result;
}
: SelectMany! , - , , , .
MSDN: SelectMany " IEnumerable ."