c# - Demonstrating the contents of an array but it populates wrong numbers - TagMerge
3Demonstrating the contents of an array but it populates wrong numbersDemonstrating the contents of an array but it populates wrong numbers

Demonstrating the contents of an array but it populates wrong numbers

Asked 5 months ago
-1
3 answers

The problem I think is with your error handling or the format of your document. Convert will actually throw an exception which will kill your entire loop if it cannot parse the current line. Say you had a simple line break in your file that created an empty line, you would try to parse it, an error is thrown, your code does nothing after it. Since I didnt have your file and I really do not feel like using visual studio instead of vscode, I replaced your streamreader with a stringreader (reads a string instead of a file but almost exactly the same) and i replaced the form with simple console writes. Outside of those changes, I gave myself some extra room in the array size since it was throwing exceptions and i wrapped the inside of the while loop in a try catch for format exceptions which is what Convert throws. After I made those changes, the outputs all worked properly. If you still dont see the values, then it is a problem with how you are using windows forms not your codes logic itself.

public static void Main()
{
    Console.WriteLine("Hello World");
    analyzeBtn_Click();
}


public static string SalesTxt = @"
1260.07
4002.52
267.21
15773.223
66655.2
555.0
7322
";





 private static void analyzeBtn_Click()
    {       
        string salesValue;
        Decimal[] sales = new decimal[8];
        int count = 0;
        decimal maxSales = Decimal.MinValue;
        decimal minSales = Decimal.MaxValue;
        decimal totalSales = 0;
        try
        { 
            StringReader  dataStream = new StringReader(SalesTxt);

            salesValue = dataStream.ReadLine();

            var total = sales.Sum();
            var average = sales.Average();
            var high = sales.Max();
            var low = sales.Min();

            while (salesValue != null)
            {
                try {
                    sales[count] = Convert.ToDecimal(salesValue);
                    
                    totalSales += sales[count];

                    if (sales[count] > maxSales)
                        maxSales = sales[count];

                    if (sales[count] < minSales)
                        minSales = sales[count];


                    count++;
                } catch (FormatException) {Console.WriteLine("\tException: '"+ salesValue + "'"); }

                salesValue = dataStream.ReadLine();
            }

            dataStream.Close();
        
            string listItems = string.Join(",\n", sales);
            
      
            Console.WriteLine(listItems);
            Console.WriteLine(totalSales);
            Console.WriteLine(maxSales);
            Console.WriteLine(minSales);
     
        } catch (Exception ex) {
            Console.WriteLine(ex);
        }
    }

Output:

Hello World
    Exception: ''
    Exception: '    '
1260.07,
4002.52,
267.21,
15773.223,
66655.2,
555.0,
7322,
0
95835.223
66655.2
267.21

EDIT:

In light of discussion, I have moved the string into a file with the appropriate name and used StreamReader just as you originally did. Using the same code as above just slightly modified, I was still able to get the correct output. enter image description here

Source: link

0

Different post models:
const ImagePost = mongoose.model('ImagePost', new Schema({ url: String }))

const TextPost = mongoose.model('TextPost', new Schema({ text: String }))
My user model looks like this:
const userSchema = new Schema({
    userName: {
        type: String,
        required: true
    },
    posts: [{
        postId: {
            type: Schema.Types.ObjectId,
            required: true,
            refPath: "postModel"
        },
        postModel: {
            type: String,
            required: true,
            enum: ['ImagePost', 'TextPost']
        }
    }]
})

const User = mongoose.model('User', userSchema)
The whey I think it should work is this but for some reason it doesn't do anything:
User.findById('5d302c7caf1b8906ccb611b6').populate('posts.postId')
Not sure if it’ll work on an array, but refPath should be something like:
refPath: "posts.postModel"
I can confirm the above fix works, here's a working script:
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);

const GITHUB_ISSUE = `test`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;

run().then(() => console.log('done')).catch(error => console.error(error.stack));

async function run() {
  await mongoose.connect(connectionString);
  await mongoose.connection.dropDatabase();

  const ImagePost = mongoose.model('ImagePost', new Schema({ url: String }))

  const TextPost = mongoose.model('TextPost', new Schema({ text: String }))

  const userSchema = new Schema({
    userName: {
        type: String,
        required: true
    },
    posts: [{
        postId: {
            type: Schema.Types.ObjectId,
            required: true,
            refPath: 'posts.postModel'
        },
        postModel: {
            type: String,
            required: true,
            enum: ['ImagePost', 'TextPost']
        }
    }]
  })

  const User = mongoose.model('User', userSchema)

  const image = await ImagePost.create({ url: 'Test' });
  const text = await TextPost.create({ text: 'foo' });

  await User.create({ userName: 'test', posts: [{ postId: image._id, postModel: 'ImagePost' }, { postId: text._id, postModel: 'TextPost' }] });

  const doc = await User.findOne().populate('posts.postId');

  console.log(require('util').inspect(doc, { depth: 10 }));
}

Source: link

0

If we have a document like this and we call Model.populate on it
//Example document
var myDocument = {
	"title":"something",
	"articles":[
		"5b6a2ab047b5883e44b27814",
		"5b6a2ab047b5883e44b27813",
		"5b6a2ab047b5883e44b27813",
		"5b6a2ab047b5883e44b27813",
		"5b6a2ab047b5883e44b27813",
		]
}


//Populate the articles
Node.populate(myDocument, {
	select:'title',
	path:'articles',
	options:{
		lean:true
	}
}, function(err, populated) {

              
});


//myDocument now looks like this (it's converted an array into an object)
var myDocument = {
	"title":"something",
	"articles":{
		"_id":"5b6a2ab047b5883e44b27814",
		"title":"title",
	}
}
Expected behaviour is this
var myDocument = {
	"title":"something",
	"articles":[
		 {
			"_id":"5b6a2ab047b5883e44b27814",
			"title":"title",
		},
		{
			"_id":"5b6a2ab047b5883e44b27814",
			"title":"title",
		},
		...
	]
}
6985.js
#!/usr/bin/env node
'use strict';

const assert = require('assert');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const conn = mongoose.connection;
const Schema = mongoose.Schema;

const articleSchema = new Schema({
  title: String,
  content: String
});

const schema = new Schema({
  name: String,
  articles: [{
    type: Schema.Types.ObjectId,
    ref: 'article'
  }]
});

const Article = mongoose.model('article', articleSchema);
const Test = mongoose.model('test', schema);

const articles = [];

for (let i = 0; i < 10; i++) {
  let t = `title${i}`;
  let c = `this is the content for article title ${i}.`;
  articles.push(new Article({ title: t, content: c }));
}

const test = new Test({ name: String, articles: articles.map(o => o._id)});

async function run() {
  assert.strictEqual(mongoose.version, '5.2.13');
  await conn.dropDatabase();
  await test.save();
  await Article.create(articles);

  let doc = await Test.findOne({});
  let popObj = {
    path: 'articles',
    select: 'title',
    options: {
      lean: true
    }
  };
  let pDoc = await Test.populate(doc, popObj);
  assert.strictEqual(pDoc.articles.length, 10);
  pDoc.articles.forEach(a => assert.strictEqual(a.content, undefined));
  console.log('All Assertions Pass.');
  return conn.close();
}

run();
Output:
issues: ./6985.js
All Assertions Pass.
issues:
const getContentSchema = targetRefPath => {
  const contentSchema = new Schema(
    {
      _contentId: {
        type: Schema.Types.ObjectId,
      },
      target: {
        type: Schema.Types.ObjectId,
        refPath: `${targetRefPath}.model`
      },
      targets: [{
        type: Schema.Types.Object,
        refPath: `${targetRefPath}.model`
      }],
      type: {
        type: String,
        required: true,
        enum: ['Exercise', 'Lesson'],
      },
    },
    {
      timestamps: true,
      _id:false,
      id:false,
      toJSON: {
        virtuals: true,
        transform: (obj, ret) => {
          delete ret._id;
        },
      },
    },
  );

  return contentSchema;
};

Source: link

Recent Questions on c#

    Programming Languages