简体   繁体   中英

Error calculating distinct values using LINQ in C#

I am using FileHandler utility to convert the CSV file to Objects(Lore).After fetching the data, the intention is to eliminate duplicates for data field someTemp. I am using LINQ query to calculate the distinct values but it gives the following error: 'object' does not contain a definition for 'someTemp' and no extension method 'someTemp' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Can someone please help.

FileHelperAsyncEngine engine = new FileHelperAsyncEngine(typeof(Lore));
            using (engine.BeginReadFile(filePath))
            {
                var distinct = engine.GroupBy(x => x.someTemp).Select(y => y.Last());enter code here
                // The engine is IEnumerable
                foreach (Lore lor in engine)
                {
                    StringBuilder str = new StringBuilder();
                    str.Append(lor.RowNumber + " ");
                    str.Append(lor.LocalDate + " ");
                    str.Append(lor.LocalTime);
                    Console.WriteLine("{0} {1} {2}",lor.RowNumber,lor.LocalDate,lor.LocalTime);
                    listBox1.Items.Add(str);
                }
            }

 [DelimitedRecord(",")]
    [IgnoreFirst]
    public class Lore
    {
        public int RowNumber;

        [FieldConverter(ConverterKind.Date,@"MM/dd/yyyy")]
        public DateTime LocalDate;

        [FieldConverter(ConverterKind.Date,"HH:mm:ss")]
        public DateTime LocalTime;

        public int Batch_Size;

        public int someTemp { get; set; }

    }   

如果在编译时知道类型,则应使用通用版本,否则将不得不强制转换结果。

var engine = new FileHelperAsyncEngine<Lore>();

nVoigt's answer is correct, the generic version is what you need, I think it will handle casting for you. If not, the correct line would be:

var distinct = engine.GroupBy(x => x.someTemp).Select(y => (y.Last()) as Lore)

or

var distinct = engine.GroupBy(x => x.someTemp).Select(y => y.Last()).Cast<Lore>()

You should only use this construction if you don't know the type at compile time, and then you would replace Lore with a type parameter T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM