Tuesday 15 January 2013

c# - Can a linq to objects SelectMany selector result in nothing added to the collection? -


I am trying to use selectMany to compile a list of lists, though the selector may get an error And so there is no result.

I am going to provide the actual function that I am trying to write and then the snippet written to explore it.

In the output code, my goal is that the serializer throws an exception.

In the sample code I have solved the problem for string case, but I'm not sure that this solution is actually more than a hack.

Product Code: Public List & lt; Click & gt; Clicks (Int Advertiser ID, Datetime Date) {var dirInfo = New DirectoryInfo (DirName (Date, Advertiser ID)); If (dirInfo.Exists) {var files = dirInfo.EnumerateFiles (); Var click = files.SelectMany (c = & gt; {using (var stream = c.OpenRead)) {return (click []) Click Serializer. Direialize (stream);}}); Click Back. List (); } Return tap; }

Sample code:

  Zero main () {var ids = new [] {1, 2, 3} ; Var name = id To catch selectmen (id = & gt; {{GetNames (return)} {} {console. WrightLine ("Error getting names for {0}", ID); // Result: on System.Linq NullReferenceException Singhal. SelectManyIterator & gt; d__14`2.MoveNext () // Returning Null; // Result: An empty string in the result, but how to do it with other types? Return the new string [] {string.Empty };}}); Foreign currency (names in names) {Console.WriteLine ("name: {0}", name); }} String [] GetNames (int id) {switch (id) {case 1: new return [] {"gym", "bob"}; Case 2: New Return [] ("Harry", "Larry"}; Default: New Exception Folder ("Invalid ID");}}    

You can return to default (t) some other type T though I'm not sure that How useful would be: Public IEnumerable & lt; T & gt; TrySelectMany & lt; T & gt; (This IEnumerable & lt; T & gt; seq, Func & lt; T, IEnumerable & lt; T & gt; selector) {return seq.SelectMany (i = & gt; {{select selector (i);} catch (exception) {return new t [] {default (t)};}}) ;} < P> I will consider returning Enumerable.Empty () in the catch block.

No comments:

Post a Comment