aybe

Hello,

I have the following,

code :

Dim contacts As XElement = XElement.Load("e:\Collection_not_parsed.xml")

Dim elList As IEnumerable(Of XElement) = From el In contacts.Descendants("ENTRY") Select el

For Each el As XElement In elList
Console.WriteLine(el.@GENRE)
Next

xml file :

< xml version="1.0" standalone="yes" >
<NewDataSet>
<ENTRY ARTIST="" AUDIO_ID="Ab8BRVNDRERUNDU2Z2ZmZmZ2Zs3t3d3d3t3d3t3u3d3d3d3d3d7t3d3d3d3t7f///////////////////////////////////////////////s7Mvcy97c3////////////////////////////////////////////////////////////////dqriJqHeqZJ7+/v7+//7u///////////////////////////////cuqqrq7u83//////////////////////////////////////////////////////////////////////93d3d3N3c3d3d3d3d3d3d3dcQAA" ID="18017" LOCK="0" TITLE="16B - The Game (Marcello Castelli Tribal Deep Mix)" DIR="/Documents/Ma musique/singles/House/Tribal/Dub/" FILE="16B - The Game (Marcello Castelli Tribal Deep Mix).mp3" PATH="E:\Documents\Ma musique\singles\House\Tribal\Dub\" VOLUME="E:" GENRE="Tribal" IMPORT_DATE="2005/12/12" KEY="C#m" PLAYCOUNT="0" PLAYTIME="447" RANKING="255" RATING="fine !" BPM="126.155731" BPM_QUALITY="37" PEAK_DB="-0.220260" PERCEIVED_DB="-0.190534" />
<ENTRY ARTIST="" AUDIO_ID="AScAh0RkSWRGRJZEZFpUSFWlRGRpVFVGpEVUeERoSbaHh5pYd4qliHipWIeblnhoqGeHm4d5ebZ3l6toeHqmh3eqWHeKpYh5umiGipZ4abhnl5t3eHq2d7m7aHqrtoequmiKu6WIqrpomauWeau4d6u9d4l7x4eYzGh5i7aWaMtZiJymmYraaZislomL2HiYvXiJi9eHmLxpeZzGmJnLaYittpiKymma3ZeZith4qb2IiYvGiJncioqctpma3HmavbeprNuKqL2Yq5rZiam8iIl814iYzGmJnMaYq9ppiMuliIm5Z4irl3mKuHeYqUMzN3MzM4czMzhTNXQhEAAAAA" ID="18019" LOCK="0" TITLE="ADNY - Omnipotent" DIR="/Documents/Ma musique/singles/House/Tribal/Dub/" FILE="ADNY - Omnipotent.mp3" PATH="E:\Documents\Ma musique\singles\House\Tribal\Dub\" VOLUME="E:" GENRE="Tribal" IMPORT_DATE="2005/12/12" KEY="D#m" PLAYCOUNT="0" PLAYTIME="295" RANKING="255" RATING="fine !" BPM="120.120308" BPM_QUALITY="56" PEAK_DB=" 0.116050" PERCEIVED_DB=" 3.829466" />
<ENTRY ARTIST="" AUDIO_ID="ATwAVDIjIiIiIiIiIiIie6mqmamamaqaqZqpqpqpqpqqmqmqmqqqq9y8y8y7y7y7zLzLvMvMvMu8u8u8u8y7ya3My7zMvLzMvMzMu8zMy8zMy83M273M27zsu7u7u7q7q7u7u7vLu6u6u6u6q6q6q7isu7u7urury7uququ8y7u7vLq7u8q7u8u93MzM3MzMzMzMzczM3dzNzNy9zNy83M283c3MzczMzdzMzdzMzd3MzM3Lzc3Lzczc3XVEQzMzMzMzMzMzNGRENDNENDNDNDNENMzNu8zMu83MzL3MvL3cvMzMu8zNy8zMy83M273My7zczMvczNyVQiEREQAAAA" ID="18021" LOCK="0" TITLE="Aztec - Summer Drummer (Nari Drumdub Mix)" DIR="/Documents/Ma musique/singles/House/Tribal/Dub/" FILE="Aztec - Summer Drummer (Nari Drumdub Mix).mp3" PATH="E:\Documents\Ma musique\singles\House\Tribal\Dub\" VOLUME="E:" GENRE="Tribal" IMPORT_DATE="2005/12/12" KEY="F m" PLAYCOUNT="0" PLAYTIME="316" RANKING="255" RATING="fine !" BPM="126.065842" BPM_QUALITY="37" PEAK_DB="-0.201453" PERCEIVED_DB="-0.220534" />

....

I have tried many possible things to get only DISTINCT values but it always outputs everything,
followed a couple of ways told in the help but none work,
do you have any idea

Thank you.



Re: LINQ Project General How can I do a SELECT DISTINCT ?

Keith Farmer

.Distinct() can take an IEqualityComparer, wherein you could describe how different XElements are to be compared (eg, by AUDIO_ID):

Code Snippet

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);

Code Snippet

namespace System.Collections.Generic

{

// Summary:

// Defines methods to support the comparison of objects for equality.

//

// Type parameters:

// T:

// The type of objects to compare.

public interface IEqualityComparer

{

bool Equals(T x, T y);

//

// Summary:

// Returns a hash code for the specified object.

//

// Parameters:

// obj:

// The System.Object for which a hash code is to be returned.

//

// Returns:

// A hash code for the specified object.

int GetHashCode(T obj);

}

}






Re: LINQ Project General How can I do a SELECT DISTINCT ?

aybe

Hello,

Sorry but i haven't understand anything !

What is the GetHashCode for


Here's another example supposed to work but it doesn't :
public static void DistinctExample()
{
string[] names = new string[] { "Peter", "Paul", "Mary",
"Peter", "Paul", "Mary", "Janet" };

var q = (from s in names
select s).Distinct();

foreach (var name in q) {
Console.WriteLine(name);
}

Console.ReadLine();
}
I have tried to do this but i didn't work either :

Dim contacts As XElement = XElement.Load("e:\Collection_not_parsed.xml")

'Dim elList As IEnumerable(Of XElement) = From el In contacts.Descendants("ENTRY") Select el

Dim elList As IEnumerable(Of XElement) = (From el In contacts.Descendants("ENTRY") Select el.@GENRE) '.Distinct()


For Each el As XElement In elList
' Console.WriteLine(el.@GENRE)
Console.WriteLine(el)
Next




System.InvalidCastException was unhandled
Message="Unable to cast object of type '<SelectIterator>d__b`2[System.Xml.Linq.XElement,System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement]'."
Source="XMLTEST"
StackTrace:
at XMLTEST.Window1.Window1_Loaded(Object sender, RoutedEventArgs e) in E:\Documents\Visual Studio Codename Orcas\Projects\XMLTEST\XMLTEST\Window1.xaml.vb:line 9
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at MS.Internal.FrameworkObject.OnLoaded(RoutedEventArgs args)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
at System.Windows.Interop.HwndTarget.OnResize()
at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at XMLTEST.Application.Main() in E:\Documents\Visual Studio Codename Orcas\Projects\XMLTEST\XMLTEST\obj\Debug\Application.g.vb:line 60
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:


I'm not gonna be able to fix it,
Do you think it is faster/smarter to use a DataTable (which i know how to use), rather than using XElement etc ... That involves an extra operation but it is much easier for me.

Do you know which way is recommended to use

Otherwise, can you provide an easy (understandable) code sample


Thanks for your help !




Re: LINQ Project General How can I do a SELECT DISTINCT ?

Martin Honnen

Here is a C# example finding unique attribute string values:

Code Snippet

XElement element = XElement.Parse("<root><foo bar=\"1\"/><foo bar=\"2\"/><foo bar=\"1\"/><foo bar=\"3\"/></root>");
var query = (from a in element.Descendants("foo").Attributes("bar") select (string)a).Distinct();
foreach (var att in query)
{
Console.WriteLine(att);
}

Finds the distinct values 1, 2, 3.






Re: LINQ Project General How can I do a SELECT DISTINCT ?

Martin Honnen

Here is the same example using VB.NET:

Code Snippet

Dim element As XElement = <root><foo bar="1"/><foo bar="2"/><foo bar="1"/><foo bar="3"/></root>
Dim query = (From s In element...<foo>.Attributes("bar") Select CType(s, String)).Distinct()
For Each s In query
Console.WriteLine(s)
Next






Re: LINQ Project General How can I do a SELECT DISTINCT ?

aybe

Hello Martin,

It's perfect, however i cannot perform an ORDER BY on the same line,

I replaced

Dim elList = (From el In contacts...<ENTRY>.Attributes("GENRE") Select CType(el, String)).Distinct()

by

Dim elList = (From el In contacts...<ENTRY>.Attributes("GENRE") Select CType(el, String) Order By .............. Ascending).Distinct()

But where are the dots, IntelliSense doesn't allow me to put "el"

Instead, this one works

Dim elList = (From el In contacts...<ENTRY>.Attributes("GENRE") Select CType(el, String)).Distinct()

Dim q2 = (From Le In elList Order By Le Ascending)

Do you know if this is possible to have this on the same line

Thanks for your help !





Re: LINQ Project General How can I do a SELECT DISTINCT ?

Martin Honnen

You will have to do the order by on the attribute value which you can access as @GENRE in VB.NET. In that case you need to adapt the From in slightly, here is the earlier example adapted:

Code Snippet

Dim element As XElement = <root><foo bar="2"/><foo bar="3"/><foo bar="1"/><foo bar="1"/></root>
Dim query = (From f In element...<foo> Order By f.@bar Select f.@bar).Distinct()
For Each s In query
Console.WriteLine(s)
Next
Console.WriteLine()
query = (From f In element...<foo> Order By f.@bar Descending Select f.@bar).Distinct()
For Each s In query
Console.WriteLine(s)
Next






Re: LINQ Project General How can I do a SELECT DISTINCT ?

aybe

Hello Martin,

Thanks, it's working, but why did you put those two lines

Dim query = (From f In element...<foo> Order By f.@bar Select f.@bar).Distinct()

query = (From f In element...<foo> Order By f.@bar Descending Select f.@bar).Distinct()

By using only the second, it still works. Is this done especially for

Otherwise, it's perfect,

Thank you





Re: LINQ Project General How can I do a SELECT DISTINCT ?

Martin Honnen

I simply wanted to give two examples, one using Order By, the second using Order By ... Descending. Choose the one you need, depending whether you want ascending or descending order.




Re: LINQ Project General How can I do a SELECT DISTINCT ?

Aybe81

Alright,

You know, you really saved me some headaches

It's not very easy to start a new language,

i'm somewhat as stuck as i used to be when i started VB,

but i'm getting better thanks to person like you helping in forums !

My last programming language was Visual Basic 1.0 for DOS .......... if i remember it was in 1992

Okay, thanks again,