1

I have a List of Objects

List<Flywheel> parts1 = new List<Flywheel>();

i want to extract an array of one of the properties.

 parts1 = parts.DistinctBy(Flywheel => Flywheel.FW_DMF_or_Solid).OrderBy(Flywheel => Flywheel.FW_DMF_or_Solid).ToList();

 string[] mydata = ((IEnumerable)parts1).Cast<Flywheel>()
                              .Select(x => x.ToString())
                              .ToArray();

the code for DistinctBy()

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }

what i get in my code is a array of string thart each of them is "XXX.Flywheels.Flywheel" but i need to get the actual values.

0

3 Answers 3

2

This should work:

List<Flywheel> parts1 = new List<Flywheel>();
var mydata = parts1.Select(x => x.FW_DMF_or_Solid).OrderBy(x => x).Distinct().ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Your ToString() operator is outputting "XXX.Flywheels.Flywheel". You need

string[] mydata = ((IEnumerable)parts1).Cast<Flywheel>()
                          .Select(x => x.FW_DMF_or_Solid.ToString())
                          .ToArray();

Also, you should be able to replace your DistinctBy code with

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    return source.GroupBy(x => keySelector(x)).Select(g => g.First());
}

Comments

0
string[] arrayOfSingleProperty = 
         listOfObjects
        .Select(o => o.FW_DMF_or_Solid)
        .OrderBy(o =>o)
        .Distinct()
        .ToArray();

2 Comments

You're performing the OrderBy operation after the Select operation. I don't think this will compile.
Good point @RobLyndon, I meant to order by the item itself... Code updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.