Archive for February, 2012

C# Short Takes – 1 – XML Comments syntax for the cref attribute to a Generic Type Method


Introduction

For the last couple of blog posts I have been using the XML Documentation feature of C# and Sandcastle to generate chm help files. This has resulted in help for methods I have been developing being available in many parts of the Visual Studio environment. Enabling Intelescensecontext sensitive help have proved to quite useful, and is a good thing to include with the source code I have been posting on the blog.

Things have been going quite well with this approach, until I ran into a problem with the <see/> tag and the cref attribute. This tag generates a hyperlink within the output files, after Sandcastle has processed them. These generated hyperlinks to methods in the documentation were a feature I wanted to enable in a couple of places within the generated documentation.

The Problem

The situation which caused me a headache was trying to make pair of <see/> tag elements in the XML Documentation which referenced each of a pair of generic methods. The method signatures were:

public static IEnumerable<TSource> ToIEnumerable(TSource val)
public static IEnumerable<TSource> ToIEnumerable(TSource val1, TSource val2)

The Solution

After trying a number of things and searching on the net, I discovered the following on stackoverflowC#, XML-Doc: Refering to a generic type of a generic type in C# XML documentation?. The last answer in to the question is the one that gave me the way to solve the problem.

Simply, what is required is the xml escaping of the <>I n the function name. For a full (I would expect) list of the xml escape sequences see: List of XML and HTML character entity references.

The resulting references in the <see/> tag end up as:

        /// <see cref="ToIEnumerable&lt;TSource&gt;(TSource)"/> 
 /// <see cref="ToIEnumerable&lt;TSource&gt;(TSource, TSource)"/> 

Reasoning Why It Works

This makes a degree of logical sense when you consider the resulting context of this attribute. The C# compiler translates the XML Documentation into a XML file. Within an XML file an attribute, or element, which contains a < or > character needs to have those characters translated into XML escape equivalents. Thus, the target of the link will be in an XML escaped form, so also the reference to the target should comply with the same XML escape sequences.

A Visual Studio Handy Hint

There is a built-in paste function, Edit.PasteAlterernate. The following blog post ‘What is Paste Alternate?’ describes what this function does. If you use this to paste a function signature from a C# file into a html file, you get the prototype with xml escapes included, plus a bunch of html. Using this paste variant may prove useful when you need a quick way of generating xml escapes .

In my version of Visual Studio, this function was unbound to a keystroke combination. Yu can use the Tools -> Options menu items to get up the dialogue box that allows setting the keystroke combination. The keystroke combinations are set in the Environment -> Keyboard section of this dialogue box.

Conclusions

I trust that reading to here, you have found blog post useful, or that it has helped solves you XML Documentation problems.

Advertisements

, , , , , , , , ,

5 Comments

LINQ Short Takes – Number 3 –LINQ over Multiple Dimension Arrays and Lists


Introduction

This blog post presents an alternative approach to using LINQ against List<Of T> and multidimensional arrays (and other types). This approach builds on the preceding blog posts LINQ Short Takes – Number 1 – Enumerable.Range() and LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product.

An Alternative Approach to Multiple Dimension Arrays and Lists

A core of this approach is to use two features of the C# language. These features are:

  1. The indexer which is available on some object types (see MSDN Article: Indexers (C# Programming Guide)), and the indexed access which the array objects support. In the case of object collections which do not support the IList(of T) interface, the LINQ extension methods ElementAt provides an equivalent, and very useable, alternative.
  2. The use of LINQ to generate the index values that are used against the collection objects supporting indexers, and array objects.

The use of LINQ to generate the index values into collections or arrays is not the approach that developers normally use with these objects. This approach has benefits in terms of clarity of the resulting code. This approach is only applicable to certain classes of problems that a developer may encounter.

Example Notes:

There are a couple of points to note about the presented examples:

  1. I have used my LINQ extension method ToOutput to produce a dump of the result sequences. This extension method was the subject of my blog post Dumping a formatted IEnumerable to Output. This blog post also includes to the source code for the extension method. Additionally, there are links to docx and pdf files of the source code.
  2. The source code for the methods which the following examples contain are available in docx and pdf files from the following URLS:
    https://craigwatson1962.files.wordpress.com/2012/02/linq-over-multiple-dimension-arrays-and-lists.docx
    https://craigwatson1962.files.wordpress.com/2012/02/linq-over-multiple-dimension-arrays-and-lists.pdf

Examples of Approach on List Collections

The following are examples of LINQ query syntax examples of using LINQ to generate and enumerate the index into a List. By using the array, or indexer, syntax to access the elements of the List(Of T) Class makes calculating the difference between adjacent dates in the List(Of T) Class trivial. The pure LINQ way to achieve this type of calculation between members of a List is not as simple, clear, or concise, as this approach.

private void LINQ_ALternative_List()
{
    List<DateTime> Dates = new List<DateTime>()
    {
        new DateTime(2012,1,1), new DateTime(2012,2,29),
        new DateTime(2012,8,13), new DateTime(2012,9,10)
    };
    var DaysGaps = from idx in Enumerable.Range(0, Dates.Count-1)
                   select Dates[idx + 1] - Dates[idx];
    Debug.WriteLine("Dumping DaysGaps");
    DaysGaps.ToOutput(FormatFunction:
        (val, position) => string.Format("[{0}]={1}\n", position, val.ToString("%d")));

    var DaysGaps1 = from idx in Enumerable.Range(0, Dates.Count - 1)
                    select (Dates[idx + 1] - Dates[idx]).Days;
    Debug.WriteLine("Dumping DaysGaps1");
    DaysGaps1.ToOutput(FormatFunction:
        (val, position) => string.Format("[{0}]={1}\n", position, val));
    return; // Allows a breakpoint at the end of the method. }

Example of Approach on Dictionary Collection

The following example demonstrates the use of ElementAt method to achieve the same days difference calculation as the preceding example. This example is manipulating the values in the Value property of the KeyValuePair contained in a Dictionary(Of TKey, TValue) Class.

private void LINQ_Alternative_Dictionary()
{
    Dictionary<int, DateTime> Dict1 = new Dictionary<int, DateTime>()
    {
        {1, new DateTime(2012, 1,  1)}, {5, new DateTime(2012, 3, 15)},
        {7, new DateTime(2012, 4, 21)}, {9, new DateTime(2012, 12, 25)}
    };
    var a = Dict1.ElementAt(2);
    var DateDiffs = from idx in Enumerable.Range(0, Dict1.Count - 1)
                    select (Dict1.ElementAt(idx + 1).Value - Dict1.ElementAt(idx).Value).Days;
    Debug.WriteLine("Dumping DateDiffs");
    DateDiffs.ToOutput(FormatFunction:
        (val, position) => string.Format("[{0}]={1}\n", position, val));

    return; // Allows a breakpoint at the end of the method. }

Examples of Approach on Multidimensional Arrays

The following is an example of using LINQ query syntax to access the elements of a 2-dimensional array. The code forms a Cartesian product between the sequences idx1 and idx2. This Cartesian product is used to access each of the elements of the array Multi1. The example creates an anonymous type (see MSDN article: Anonymous Types (C# Programming Guide) for further information) which contains the indexes and array element value.

There are a couple of other notable points:

  1. The use of the Array.GetLength Method to discover the number of elements that are required in the array index sequences. The use of the Array.GetLength Method results in code that is more robust.
  2. This example demonstrates accessing a 2-dimensional array. A similar pattern will work for any number of array dimensions.
  3. 3. Arrays with more than one dimension do not support the IEnumerable(Of T) Interface. This results in multidimensional arrays not natively, or supported by the implementation of the .Net Framework (see MSDN article: Overview of the .NET Framework for further information). This results in multidimensional arrays not being usable as a LINQ data source. If you attempt to use a multidimensional array as a data source (from ) results in the error CS1935. The following is the full error message
    error CS1935: Could not find an implementation of the query pattern for source type ‘int[*,*]’. ‘Select’ not found. Are you missing a reference to ‘System.Core.dll’ or a using directive for ‘System.Linq’?
private void LINQ_ALternative_Array()
{
    int[,] Multi1 = new int[,]
    {
        {1,2,3}, {4,5,6}, {7,8,9}
    };
    var dump1 = from idx1 in Enumerable.Range(0, Multi1.GetLength(0))
                from idx2 in Enumerable.Range(0, Multi1.GetLength(1))
                select new { idx1, idx2, val = Multi1[idx1, idx2] };
    Debug.WriteLine("Dumping dump1");
    dump1.ToOutput(FormatFunction:
        (val, position) => string.Format("[{0}] [{1},{2}]={3}\n", position, val.idx1, val.idx2, val.val));

    return; // Allows a breakpoint at the end of the method. }

Conclusion

I hope that this blog post and the preceding two blog posts in this series LINQ Short Takes – Number 1 – Enumerable.Range() and LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product have added something useful to your kit bag of LINQ tools and techniques.

The approach to working with collections and arrays through an index (or indexes) is one that is applicable to a class of problems that I have not seen used elsewhere. That is not to says that I have conducted an exhaustively search of the web for other examples of this approach.

For those readers who have read LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product, and are interested. I indicted in that blog post I would think about an extension method implementation of a general solution to creation of Cartesian products using the Enumerable.Join Method. Well, I wrote that extension method this morning, and will ‘clean it up’, write some XML documentation, and post the solution on this blog sometime soon.

, , , , , , , , , , , , ,

3 Comments

LINQ Short Takes – Number 2 – Using Method Syntax to Create a Cartesian Product


Introduction

This is the second post in a series (I have no idea how many blog posts this series may comprise) of LINQ Short Takes. The first post was LINQ Short Takes – Number 1 – Enumerable.Range() which presented the Enumerable.Range() method. This blog post utilises the Enumerable.Range() method to form a Cartesian product utilising the LINQ method syntax (see: MSDN (Microsoft Developer Network Web Site) Article – LINQ Query Syntax versus Method Syntax (C#)for further discussion of the topic).

The motivation for developing this approach was twofold:

1. I did need a sequence of integers that formed a Cartesian product.

2. I experienced a degree of exasperation, frustration and downright ‘that’s wrong and very tacky’ when I looked for LINQ Cartesian Products using Method syntax. The solutions I read used a SelectMany()and lacked clarity that any good code should have.

So, I decided that there must be a simpler way to form a Cartesian product from two sequences using LINQ method calls. What has resulted is a solution to the problem that, in my opinion, is clear and concise. The solutions implementation uses a LINQ Join() method call to build the Cartesian product.

Cartesian Products

Please excuse the diversion into a little bit set theory. This diversion explains why the LINQ Join() method succeeds in forming a Cartesian product.

A Cartesian productis a resulting sequence of two input sequences. The output sequence has that all elements in the first sequence join with each element of the second sequence. The resulting sequence is series of element pairs from both input sequences. The length of the output sequence is the product of the lengths of the two input sequences.

The join operation between the two sequences that form the Cartesian producthas the following properties. If all of the elements in the two input sequences match each other, we have a type of join with a special property. This type of join’s special property implies that the join key for all of the elements in the two sequences is the same value.

Armed with the conclusion that a Cartesian product has the join key for both inputs sequences should be the same value. The process of forming a C# statement which utilises the Join() method to form a Cartesian product between the two input sequences becomes a simple process.

Example Code

The following C# method contains three examples of forming a Cartesian product. I will comment a little more on the three examples after the code.

The code also utilises the LINQ extension method ToOutput. This was the subject of a previous blog post: Dumping a formatted IEnumerable to Output.

I have loaded this code in Work docx and pfd formats as well. The URL’s are:
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproducts.docx
https://craigwatson1962.files.wordpress.com/2012/02/cartesianproducts.pdf

private void CartesianProducts()
{
    // Query Syntax Cartesian Product var Prod1 = from num1 in Enumerable.Range(0, 10)
                from num2 in Enumerable.Range(0, 10)
                select new { num1, num2 };
    Debug.WriteLine("/nDump of Prod1");
    // Dump the contents of Prod1 Prod1.ToOutput(FormatFunction:
        (objValue, Position) =>
        {
            return string.Format("[{0}] {1},{2}\n",
                Position, objValue.num1, objValue.num2);
        });

    // Generate a Cartesian product using LINQ method syntax from two sequences var Prod2 = Enumerable.Range(0, 10).Join(Enumerable.Range(0,10),
        (iVal1) => 1, // Key selectors make all elements in first sequence (iVal2) => 1, // match all elements in the second sequence. (iVal1, iVal2) =>
            new {iVal1, iVal2}); // Create an object with the two values. Debug.WriteLine("/nDump of Prod2");
    // Dump the contents of Prod2 Prod2.ToOutput(FormatFunction:
        (objValue, Position) =>
        {
            return string.Format("[{0}] {1},{2}\n",
                Position, objValue.iVal1, objValue.iVal2);
        });

    string[] SampleStrings = new string[]
    { "The", "quick", "red", "fox", "jumped",
        "over", "the", "lazy", "brown", "cow" };
    // Generate a 3 way Cartesian product var Prod3 = Enumerable.Range(0, 10)
                    .Join(Enumerable.Range(0, 5), iVal1 => 1, iVal2 => 1,
                        (iVal1, iVal2) => new { iVal1, iVal2 })
                    .Join(SampleStrings, iVals => 1, strVals => 1,
                        (iVals, strVal) =>
                            new {
                                intValue1 = iVals.iVal1,
                                intValue2 = iVals.iVal2,
                                strValue = strVal });
    Debug.WriteLine("/nDump of Prod3");
    // Dump the contents of Prod3 Prod3.ToOutput(FormatFunction:
        (objVal, Position) =>
            string.Format("[0] {1},{2},'{3}'\n",
                Position, objVal.intValue1, objVal.intValue2, objVal.strValue));
    Debug.WriteLine(string.Format(
        "Double Check\n\tSequence1 Length {0} Sequence2 Length {1}" +
        "SampleStrings Length{2}\n\t" +
        "Input Sequence Product Value {3} Result Length {4}",
        Enumerable.Range(0, 10).Count(),
        Enumerable.Range(0, 5).Count(),
        SampleStrings.Count(),
        Enumerable.Range(0, 10).Count()
            * Enumerable.Range(0, 5).Count()
            * SampleStrings.Count(),
        Prod3.Count()));

    return;
}

The examples of forming a Cartesian product with LINQ are:

  1. This example uses the LINQ query syntax to create a Cartesian product. It uses an unconstrained join between the two sequences. This is exactly how SQL operates when used to form a Cartesian product.
  2. The second example uses the LINQ method syntax to form a Cartesian product between two integer sequences. These sequences are generated using the Enumerable.Range () method. The Cartesian product is formed using the LINQ method Join(). The arguments to the overload of the Join() methods are: the second IEnumerable, the outer (first sequence) key selector, the inner (the second sequence) key selector, and the result selector. The key selectors in each part of the join are just 1, which ‘says’ this is the join key for each of the same sequences.
  3. The third example demonstrates the scalability of the approach, by joining three sequences in a Cartesian product. If you can do this with two, and three sequences, then I would expect the approach would work with as many sequences as you require. This example also demonstrates the joining of different types of object using this approach.

If you missed it above, this example method also uses the ToOutput LINQ extension method. The ToOutput extension method was the subject of a previous blog post: Dumping a formatted IEnumerable to Output, and the code for the extension method is included there.

Conclusions

  • I believe that the approach presented is a clear, clean, and concise, approach to generation of a Cartesian product using the LINQ method syntax.
  • I suspect that I will generalise this approach into another LINQ extension method. The may well become another blog post. There are a couple of interesting deign decisions which I need to make when designing and implementing this approach as an extension method. I will leave those discussions for that blog post.

, , , , , , , ,

3 Comments

%d bloggers like this: